Common.cpp 134 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523
  1. //---------------------------------------------------------------------------
  2. #define NO_WIN32_LEAN_AND_MEAN
  3. #include <vcl.h>
  4. #pragma hdrstop
  5. #include "Common.h"
  6. #include "Exceptions.h"
  7. #include "TextsCore.h"
  8. #include "Interface.h"
  9. #include <StrUtils.hpp>
  10. #include <DateUtils.hpp>
  11. #include <System.IOUtils.hpp>
  12. #include <math.h>
  13. #include <shlobj.h>
  14. #include <limits>
  15. #include <algorithm>
  16. #include <shlwapi.h>
  17. #include <tlhelp32.h>
  18. #include <psapi.h>
  19. #include <CoreMain.h>
  20. #include <SessionInfo.h>
  21. #include <Soap.EncdDecd.hpp>
  22. #include <openssl/pkcs12.h>
  23. #include <openssl/pem.h>
  24. #include <openssl/err.h>
  25. #include <openssl/ssl.h>
  26. //---------------------------------------------------------------------------
  27. #pragma package(smart_init)
  28. //---------------------------------------------------------------------------
  29. const wchar_t * DSTModeNames = L"Win;Unix;Keep";
  30. //---------------------------------------------------------------------------
  31. //---------------------------------------------------------------------------
  32. const UnicodeString AnyMask = L"*.*";
  33. const wchar_t EngShortMonthNames[12][4] =
  34. {L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun",
  35. L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec"};
  36. const char Bom[3] = "\xEF\xBB\xBF";
  37. const wchar_t TokenPrefix = L'%';
  38. const wchar_t NoReplacement = wchar_t(false);
  39. const wchar_t TokenReplacement = wchar_t(true);
  40. // Note similar list in MakeValidFileName
  41. const UnicodeString LocalInvalidChars(TraceInitStr(L"/\\:*?\"<>|"));
  42. const UnicodeString PasswordMask(TraceInitStr(L"***"));
  43. const UnicodeString Ellipsis(TraceInitStr(L"..."));
  44. const UnicodeString TitleSeparator(TraceInitStr(L" \u2013 ")); // En-Dash
  45. const UnicodeString OfficialPackage(TraceInitStr(L"MartinPikryl.WinSCP_tvv458r3h9r5m"));
  46. //---------------------------------------------------------------------------
  47. UnicodeString ReplaceChar(UnicodeString Str, wchar_t A, wchar_t B)
  48. {
  49. for (Integer Index = 0; Index < Str.Length(); Index++)
  50. if (Str[Index+1] == A) Str[Index+1] = B;
  51. return Str;
  52. }
  53. //---------------------------------------------------------------------------
  54. UnicodeString DeleteChar(UnicodeString Str, wchar_t C)
  55. {
  56. int P;
  57. while ((P = Str.Pos(C)) > 0)
  58. {
  59. Str.Delete(P, 1);
  60. }
  61. return Str;
  62. }
  63. //---------------------------------------------------------------------------
  64. template<typename T>
  65. void DoPackStr(T & Str)
  66. {
  67. // Following will free unnecessary bytes
  68. Str = Str.c_str();
  69. }
  70. //---------------------------------------------------------------------------
  71. void PackStr(UnicodeString & Str)
  72. {
  73. DoPackStr(Str);
  74. }
  75. //---------------------------------------------------------------------------
  76. void PackStr(RawByteString & Str)
  77. {
  78. DoPackStr(Str);
  79. }
  80. //---------------------------------------------------------------------------
  81. void PackStr(AnsiString & Str)
  82. {
  83. DoPackStr(Str);
  84. }
  85. //---------------------------------------------------------------------------
  86. template<typename T>
  87. void __fastcall DoShred(T & Str)
  88. {
  89. if (!Str.IsEmpty())
  90. {
  91. Str.Unique();
  92. memset(Str.c_str(), 0, Str.Length() * sizeof(*Str.c_str()));
  93. Str = L"";
  94. }
  95. }
  96. //---------------------------------------------------------------------------
  97. void __fastcall Shred(UnicodeString & Str)
  98. {
  99. DoShred(Str);
  100. }
  101. //---------------------------------------------------------------------------
  102. void __fastcall Shred(UTF8String & Str)
  103. {
  104. DoShred(Str);
  105. }
  106. //---------------------------------------------------------------------------
  107. void __fastcall Shred(AnsiString & Str)
  108. {
  109. DoShred(Str);
  110. }
  111. //---------------------------------------------------------------------------
  112. void __fastcall Shred(RawByteString & Str)
  113. {
  114. DoShred(Str);
  115. }
  116. //---------------------------------------------------------------------------
  117. UnicodeString AnsiToString(const RawByteString & S)
  118. {
  119. return UnicodeString(AnsiString(S));
  120. }
  121. //---------------------------------------------------------------------------
  122. UnicodeString AnsiToString(const char * S, size_t Len)
  123. {
  124. return UnicodeString(AnsiString(S, Len));
  125. }
  126. //---------------------------------------------------------------------------
  127. // Note similar function ValidLocalFileName
  128. UnicodeString MakeValidFileName(UnicodeString FileName)
  129. {
  130. // Note similar list in LocalInvalidChars
  131. UnicodeString IllegalChars = L":;,=+<>|\"[] \\/?*";
  132. for (int Index = 0; Index < IllegalChars.Length(); Index++)
  133. {
  134. FileName = ReplaceChar(FileName, IllegalChars[Index+1], L'-');
  135. }
  136. return FileName;
  137. }
  138. //---------------------------------------------------------------------------
  139. UnicodeString RootKeyToStr(HKEY RootKey)
  140. {
  141. if (RootKey == HKEY_USERS) return L"HKU";
  142. else
  143. if (RootKey == HKEY_LOCAL_MACHINE) return L"HKLM";
  144. else
  145. if (RootKey == HKEY_CURRENT_USER) return L"HKCU";
  146. else
  147. if (RootKey == HKEY_CLASSES_ROOT) return L"HKCR";
  148. else
  149. if (RootKey == HKEY_CURRENT_CONFIG) return L"HKCC";
  150. else
  151. if (RootKey == HKEY_DYN_DATA) return L"HKDD";
  152. else
  153. { Abort(); return L""; };
  154. }
  155. //---------------------------------------------------------------------------
  156. UnicodeString BooleanToEngStr(bool B)
  157. {
  158. if (B)
  159. {
  160. return L"Yes";
  161. }
  162. else
  163. {
  164. return L"No";
  165. }
  166. }
  167. //---------------------------------------------------------------------------
  168. UnicodeString BooleanToStr(bool B)
  169. {
  170. if (B)
  171. {
  172. return LoadStr(YES_STR);
  173. }
  174. else
  175. {
  176. return LoadStr(NO_STR);
  177. }
  178. }
  179. //---------------------------------------------------------------------------
  180. UnicodeString DefaultStr(const UnicodeString & Str, const UnicodeString & Default)
  181. {
  182. if (!Str.IsEmpty())
  183. {
  184. return Str;
  185. }
  186. else
  187. {
  188. return Default;
  189. }
  190. }
  191. //---------------------------------------------------------------------------
  192. // For alternative with quoting support, see TFTPFileSystem::CutFeature
  193. UnicodeString CutToChar(UnicodeString &Str, wchar_t Ch, bool Trim)
  194. {
  195. Integer P = Str.Pos(Ch);
  196. UnicodeString Result;
  197. if (P)
  198. {
  199. Result = Str.SubString(1, P-1);
  200. Str.Delete(1, P);
  201. }
  202. else
  203. {
  204. Result = Str;
  205. Str = L"";
  206. }
  207. if (Trim)
  208. {
  209. Result = Result.TrimRight();
  210. Str = Str.TrimLeft();
  211. }
  212. return Result;
  213. }
  214. //---------------------------------------------------------------------------
  215. UnicodeString CopyToChars(const UnicodeString & Str, int & From, UnicodeString Chs, bool Trim,
  216. wchar_t * Delimiter, bool DoubleDelimiterEscapes)
  217. {
  218. UnicodeString Result;
  219. int P;
  220. for (P = From; P <= Str.Length(); P++)
  221. {
  222. if (IsDelimiter(Chs, Str, P))
  223. {
  224. if (DoubleDelimiterEscapes &&
  225. (P < Str.Length()) &&
  226. IsDelimiter(Chs, Str, P + 1) &&
  227. (Str[P + 1] == Str[P]))
  228. {
  229. Result += Str[P];
  230. P++;
  231. }
  232. else
  233. {
  234. break;
  235. }
  236. }
  237. else
  238. {
  239. Result += Str[P];
  240. }
  241. }
  242. if (P <= Str.Length())
  243. {
  244. if (Delimiter != NULL)
  245. {
  246. *Delimiter = Str[P];
  247. }
  248. }
  249. else
  250. {
  251. if (Delimiter != NULL)
  252. {
  253. *Delimiter = L'\0';
  254. }
  255. }
  256. // even if we reached the end, return index, as if there were the delimiter,
  257. // so caller can easily find index of the end of the piece by subtracting
  258. // 2 from From (as long as he did not asked for trimming)
  259. From = P+1;
  260. if (Trim)
  261. {
  262. Result = Result.TrimRight();
  263. while ((From <= Str.Length()) && (Str[From] == L' '))
  264. {
  265. From++;
  266. }
  267. }
  268. return Result;
  269. }
  270. //---------------------------------------------------------------------------
  271. UnicodeString CopyToChar(const UnicodeString & Str, wchar_t Ch, bool Trim)
  272. {
  273. int From = 1;
  274. return CopyToChars(Str, From, UnicodeString(Ch), Trim);
  275. }
  276. //---------------------------------------------------------------------------
  277. UnicodeString RemoveSuffix(const UnicodeString & Str, const UnicodeString & Suffix, bool RemoveNumbersAfterSuffix)
  278. {
  279. UnicodeString Result = Str;
  280. UnicodeString Buf = Str;
  281. if (RemoveNumbersAfterSuffix)
  282. {
  283. while (!Buf.IsEmpty() && IsDigit(Buf[Buf.Length()]))
  284. {
  285. Buf.SetLength(Buf.Length() - 1);
  286. }
  287. }
  288. if (EndsStr(Suffix, Buf))
  289. {
  290. Result.SetLength(Buf.Length() - Suffix.Length());
  291. }
  292. return Result;
  293. }
  294. //---------------------------------------------------------------------------
  295. UnicodeString DelimitStr(const UnicodeString & Str, wchar_t Quote)
  296. {
  297. UnicodeString SpecialChars;
  298. if (Quote != L'\'')
  299. {
  300. SpecialChars = L"$\\";
  301. if (Quote == L'"')
  302. {
  303. SpecialChars += L"`\"";
  304. }
  305. }
  306. UnicodeString Result(Str);
  307. for (int i = 1; i <= Result.Length(); i++)
  308. {
  309. if (Result.IsDelimiter(SpecialChars, i))
  310. {
  311. Result.Insert(L"\\", i);
  312. i++;
  313. }
  314. }
  315. if (Result.IsDelimiter(L"-", 1))
  316. {
  317. Result.Insert(L"./", 1);
  318. }
  319. return Result;
  320. }
  321. //---------------------------------------------------------------------------
  322. UnicodeString MidStr(const UnicodeString & Text, int Start)
  323. {
  324. return Text.SubString(Start, Text.Length() - Start + 1);
  325. }
  326. //---------------------------------------------------------------------------
  327. UnicodeString ShellQuoteStr(const UnicodeString & Str)
  328. {
  329. wchar_t Quote = L'"';
  330. UnicodeString QuoteStr(Quote);
  331. return QuoteStr + DelimitStr(Str, Quote) + QuoteStr;
  332. }
  333. //---------------------------------------------------------------------------
  334. UnicodeString ExceptionLogString(Exception *E)
  335. {
  336. DebugAssert(E);
  337. if (E->InheritsFrom(__classid(Exception)))
  338. {
  339. UnicodeString Msg;
  340. Msg = FORMAT(L"(%s) %s", (E->ClassName(), E->Message));
  341. if (E->InheritsFrom(__classid(ExtException)))
  342. {
  343. TStrings * MoreMessages = ((ExtException*)E)->MoreMessages;
  344. if (MoreMessages)
  345. {
  346. Msg += L"\n" +
  347. ReplaceStr(MoreMessages->Text, L"\r", L"");
  348. }
  349. }
  350. return Msg;
  351. }
  352. else
  353. {
  354. wchar_t Buffer[1024];
  355. ExceptionErrorMessage(ExceptObject(), ExceptAddr(), Buffer, LENOF(Buffer));
  356. return UnicodeString(Buffer);
  357. }
  358. }
  359. //---------------------------------------------------------------------------
  360. UnicodeString __fastcall MainInstructions(const UnicodeString & S)
  361. {
  362. UnicodeString MainMsgTag = LoadStr(MAIN_MSG_TAG);
  363. return MainMsgTag + S + MainMsgTag;
  364. }
  365. //---------------------------------------------------------------------------
  366. bool __fastcall HasParagraphs(const UnicodeString & S)
  367. {
  368. return (S.Pos(L"\n\n") > 0);
  369. }
  370. //---------------------------------------------------------------------------
  371. UnicodeString __fastcall MainInstructionsFirstParagraph(const UnicodeString & S)
  372. {
  373. // WORKAROUND, we consider it bad practice, the highlighting should better
  374. // be localized (but maybe we change our mind later)
  375. UnicodeString Result;
  376. int Pos = S.Pos(L"\n\n");
  377. // we would not be calling this on single paragraph message
  378. if (DebugAlwaysTrue(Pos > 0))
  379. {
  380. Result =
  381. MainInstructions(S.SubString(1, Pos - 1)) +
  382. S.SubString(Pos, S.Length() - Pos + 1);
  383. }
  384. else
  385. {
  386. Result = MainInstructions(S);
  387. }
  388. return Result;
  389. }
  390. //---------------------------------------------------------------------------
  391. bool ExtractMainInstructions(UnicodeString & S, UnicodeString & MainInstructions)
  392. {
  393. bool Result = false;
  394. UnicodeString MainMsgTag = LoadStr(MAIN_MSG_TAG);
  395. if (StartsStr(MainMsgTag, S))
  396. {
  397. int EndTagPos =
  398. S.SubString(MainMsgTag.Length() + 1, S.Length() - MainMsgTag.Length()).Pos(MainMsgTag);
  399. if (EndTagPos > 0)
  400. {
  401. MainInstructions = S.SubString(MainMsgTag.Length() + 1, EndTagPos - 1);
  402. S.Delete(1, EndTagPos + (2 * MainMsgTag.Length()) - 1);
  403. Result = true;
  404. }
  405. }
  406. DebugAssert(MainInstructions.Pos(MainMsgTag) == 0);
  407. DebugAssert(S.Pos(MainMsgTag) == 0);
  408. return Result;
  409. }
  410. //---------------------------------------------------------------------------
  411. static int FindInteractiveMsgStart(const UnicodeString & S)
  412. {
  413. int Result = 0;
  414. UnicodeString InteractiveMsgTag = LoadStr(INTERACTIVE_MSG_TAG);
  415. if (EndsStr(InteractiveMsgTag, S) &&
  416. (S.Length() >= 2 * InteractiveMsgTag.Length()))
  417. {
  418. Result = S.Length() - 2 * InteractiveMsgTag.Length() + 1;
  419. while ((Result > 0) && (S.SubString(Result, InteractiveMsgTag.Length()) != InteractiveMsgTag))
  420. {
  421. Result--;
  422. }
  423. }
  424. return Result;
  425. }
  426. //---------------------------------------------------------------------------
  427. UnicodeString RemoveMainInstructionsTag(UnicodeString S)
  428. {
  429. UnicodeString MainInstruction;
  430. if (ExtractMainInstructions(S, MainInstruction))
  431. {
  432. S = MainInstruction + S;
  433. }
  434. return S;
  435. }
  436. //---------------------------------------------------------------------------
  437. UnicodeString UnformatMessage(UnicodeString S)
  438. {
  439. S = RemoveMainInstructionsTag(S);
  440. int InteractiveMsgStart = FindInteractiveMsgStart(S);
  441. if (InteractiveMsgStart > 0)
  442. {
  443. S = S.SubString(1, InteractiveMsgStart - 1);
  444. }
  445. return S;
  446. }
  447. //---------------------------------------------------------------------------
  448. UnicodeString RemoveInteractiveMsgTag(UnicodeString S)
  449. {
  450. int InteractiveMsgStart = FindInteractiveMsgStart(S);
  451. if (InteractiveMsgStart > 0)
  452. {
  453. UnicodeString InteractiveMsgTag = LoadStr(INTERACTIVE_MSG_TAG);
  454. S.Delete(InteractiveMsgStart, InteractiveMsgTag.Length());
  455. S.Delete(S.Length() - InteractiveMsgTag.Length() + 1, InteractiveMsgTag.Length());
  456. }
  457. return S;
  458. }
  459. //---------------------------------------------------------------------------
  460. UnicodeString RemoveEmptyLines(const UnicodeString & S)
  461. {
  462. return
  463. ReplaceStr(
  464. ReplaceStr(S.TrimRight(), L"\n\n", L"\n"),
  465. L"\n \n", L"\n");
  466. }
  467. //---------------------------------------------------------------------------
  468. bool IsNumber(const UnicodeString Str)
  469. {
  470. bool Result = (Str.Length() > 0);
  471. for (int Index = 1; (Index < Str.Length()) && Result; Index++)
  472. {
  473. wchar_t C = Str[Index];
  474. if ((C < L'0') || (C > L'9'))
  475. {
  476. Result = false;
  477. }
  478. }
  479. return Result;
  480. }
  481. //---------------------------------------------------------------------------
  482. UnicodeString EncodeStrToBase64(const RawByteString & Str)
  483. {
  484. UnicodeString Result = EncodeBase64(Str.c_str(), Str.Length());
  485. Result = ReplaceStr(Result, sLineBreak, EmptyStr);
  486. return Result;
  487. }
  488. //---------------------------------------------------------------------------
  489. RawByteString DecodeBase64ToStr(const UnicodeString & Str)
  490. {
  491. TBytes Bytes = DecodeBase64(Str);
  492. // This might be the same as TEncoding::ASCII->GetString.
  493. // const_cast: The operator[] const is (badly?) implemented to return by value
  494. return RawByteString(reinterpret_cast<const char *>(&const_cast<TBytes &>(Bytes)[0]), Bytes.Length);
  495. }
  496. //---------------------------------------------------------------------------
  497. UnicodeString Base64ToUrlSafe(const UnicodeString & S)
  498. {
  499. UnicodeString Result = S;
  500. while (EndsStr(L"=", Result))
  501. {
  502. Result.SetLength(Result.Length() - 1);
  503. }
  504. // See https://en.wikipedia.org/wiki/Base64#Implementations_and_history
  505. Result = ReplaceChar(Result, L'+', L'-');
  506. Result = ReplaceChar(Result, L'/', L'_');
  507. return Result;
  508. }
  509. //---------------------------------------------------------------------------
  510. const wchar_t NormalizedFingerprintSeparator = L'-';
  511. //---------------------------------------------------------------------------
  512. UnicodeString MD5ToUrlSafe(const UnicodeString & S)
  513. {
  514. return ReplaceChar(S, L':', NormalizedFingerprintSeparator);
  515. }
  516. //---------------------------------------------------------------------------
  517. bool SameChecksum(const UnicodeString & AChecksum1, const UnicodeString & AChecksum2, bool Base64)
  518. {
  519. UnicodeString Checksum1(AChecksum1);
  520. UnicodeString Checksum2(AChecksum2);
  521. bool Result;
  522. if (Base64)
  523. {
  524. Checksum1 = Base64ToUrlSafe(Checksum1);
  525. Checksum2 = Base64ToUrlSafe(Checksum2);
  526. Result = SameStr(Checksum1, Checksum2);
  527. }
  528. else
  529. {
  530. Checksum1 = MD5ToUrlSafe(Checksum1);
  531. Checksum2 = MD5ToUrlSafe(Checksum2);
  532. Result = SameText(Checksum1, Checksum2);
  533. }
  534. return Result;
  535. }
  536. //---------------------------------------------------------------------------
  537. UnicodeString __fastcall SystemTemporaryDirectory()
  538. {
  539. UnicodeString TempDir;
  540. TempDir.SetLength(MAX_PATH);
  541. TempDir.SetLength(GetTempPath(MAX_PATH, TempDir.c_str()));
  542. return TempDir;
  543. }
  544. //---------------------------------------------------------------------------
  545. UnicodeString __fastcall GetShellFolderPath(int CSIdl)
  546. {
  547. UnicodeString Result;
  548. wchar_t Path[2 * MAX_PATH + 10] = L"\0";
  549. if (SUCCEEDED(SHGetFolderPath(NULL, CSIdl, NULL, SHGFP_TYPE_CURRENT, Path)))
  550. {
  551. Result = Path;
  552. }
  553. return Result;
  554. }
  555. //---------------------------------------------------------------------------
  556. static UnicodeString __fastcall GetWineHomeFolder()
  557. {
  558. UnicodeString Result;
  559. UnicodeString WineHostHome = GetEnvironmentVariable(L"WINE_HOST_HOME");
  560. if (!WineHostHome.IsEmpty())
  561. {
  562. Result = L"Z:" + FromUnixPath(WineHostHome);
  563. }
  564. else
  565. {
  566. // Should we use WinAPI GetUserName() instead?
  567. UnicodeString UserName = GetEnvironmentVariable(L"USERNAME");
  568. if (!UserName.IsEmpty())
  569. {
  570. Result = L"Z:\\home\\" + UserName;
  571. }
  572. }
  573. if (!DirectoryExists(Result))
  574. {
  575. Result = L"";
  576. }
  577. return Result;
  578. }
  579. //---------------------------------------------------------------------------
  580. UnicodeString __fastcall GetPersonalFolder()
  581. {
  582. UnicodeString Result = GetShellFolderPath(CSIDL_PERSONAL);
  583. if (IsWine())
  584. {
  585. UnicodeString WineHome = GetWineHomeFolder();
  586. if (!WineHome.IsEmpty())
  587. {
  588. // if at least home exists, use it
  589. Result = WineHome;
  590. // but try to go deeper to "Documents"
  591. UnicodeString WineDocuments =
  592. IncludeTrailingBackslash(WineHome) + L"Documents";
  593. if (DirectoryExists(WineDocuments))
  594. {
  595. Result = WineDocuments;
  596. }
  597. }
  598. }
  599. return Result;
  600. }
  601. //---------------------------------------------------------------------------
  602. UnicodeString __fastcall GetDesktopFolder()
  603. {
  604. UnicodeString Result = GetShellFolderPath(CSIDL_DESKTOPDIRECTORY);
  605. if (IsWine())
  606. {
  607. UnicodeString WineHome = GetWineHomeFolder();
  608. if (!WineHome.IsEmpty())
  609. {
  610. UnicodeString WineDesktop =
  611. IncludeTrailingBackslash(WineHome) + L"Desktop";
  612. if (DirectoryExists(WineHome))
  613. {
  614. Result = WineDesktop;
  615. }
  616. }
  617. }
  618. return Result;
  619. }
  620. //---------------------------------------------------------------------------
  621. // Particularly needed when using file name selected by TFilenameEdit,
  622. // as it wraps a path to double-quotes, when there is a space in the path.
  623. UnicodeString __fastcall StripPathQuotes(const UnicodeString Path)
  624. {
  625. if ((Path.Length() >= 2) &&
  626. (Path[1] == L'\"') && (Path[Path.Length()] == L'\"'))
  627. {
  628. return Path.SubString(2, Path.Length() - 2);
  629. }
  630. else
  631. {
  632. return Path;
  633. }
  634. }
  635. //---------------------------------------------------------------------------
  636. UnicodeString __fastcall AddQuotes(UnicodeString Str)
  637. {
  638. if (Str.Pos(L" ") > 0)
  639. {
  640. Str = L"\"" + Str + L"\"";
  641. }
  642. return Str;
  643. }
  644. //---------------------------------------------------------------------------
  645. UnicodeString __fastcall AddPathQuotes(UnicodeString Path)
  646. {
  647. Path = StripPathQuotes(Path);
  648. return AddQuotes(Path);
  649. }
  650. //---------------------------------------------------------------------------
  651. static wchar_t * __fastcall ReplaceChar(
  652. UnicodeString & FileName, wchar_t * InvalidChar, wchar_t InvalidCharsReplacement)
  653. {
  654. int Index = InvalidChar - FileName.c_str() + 1;
  655. if (InvalidCharsReplacement == TokenReplacement)
  656. {
  657. // currently we do not support unicode chars replacement
  658. if (FileName[Index] > 0xFF)
  659. {
  660. EXCEPTION;
  661. }
  662. FileName.Insert(ByteToHex(static_cast<unsigned char>(FileName[Index])), Index + 1);
  663. FileName[Index] = TokenPrefix;
  664. InvalidChar = FileName.c_str() + Index + 2;
  665. }
  666. else
  667. {
  668. FileName[Index] = InvalidCharsReplacement;
  669. InvalidChar = FileName.c_str() + Index;
  670. }
  671. return InvalidChar;
  672. }
  673. //---------------------------------------------------------------------------
  674. // Note similar function MakeValidFileName
  675. UnicodeString __fastcall ValidLocalFileName(UnicodeString FileName)
  676. {
  677. return ValidLocalFileName(FileName, L'_', L"", LocalInvalidChars);
  678. }
  679. //---------------------------------------------------------------------------
  680. UnicodeString __fastcall ValidLocalFileName(
  681. UnicodeString FileName, wchar_t InvalidCharsReplacement,
  682. const UnicodeString & TokenizibleChars, const UnicodeString & LocalInvalidChars)
  683. {
  684. if (InvalidCharsReplacement != NoReplacement)
  685. {
  686. bool ATokenReplacement = (InvalidCharsReplacement == TokenReplacement);
  687. const wchar_t * Chars =
  688. (ATokenReplacement ? TokenizibleChars : LocalInvalidChars).c_str();
  689. wchar_t * InvalidChar = FileName.c_str();
  690. while ((InvalidChar = wcspbrk(InvalidChar, Chars)) != NULL)
  691. {
  692. int Pos = (InvalidChar - FileName.c_str() + 1);
  693. wchar_t Char;
  694. if (ATokenReplacement &&
  695. (*InvalidChar == TokenPrefix) &&
  696. (((FileName.Length() - Pos) <= 1) ||
  697. (((Char = static_cast<wchar_t>(HexToByte(FileName.SubString(Pos + 1, 2)))) == L'\0') ||
  698. (TokenizibleChars.Pos(Char) == 0))))
  699. {
  700. InvalidChar++;
  701. }
  702. else
  703. {
  704. InvalidChar = ReplaceChar(FileName, InvalidChar, InvalidCharsReplacement);
  705. }
  706. }
  707. // Windows trim trailing space or dot, hence we must encode it to preserve it
  708. if (!FileName.IsEmpty() &&
  709. ((FileName[FileName.Length()] == L' ') ||
  710. (FileName[FileName.Length()] == L'.')))
  711. {
  712. ReplaceChar(FileName, FileName.c_str() + FileName.Length() - 1, InvalidCharsReplacement);
  713. }
  714. if (IsReservedName(FileName))
  715. {
  716. int P = FileName.Pos(".");
  717. if (P == 0)
  718. {
  719. P = FileName.Length() + 1;
  720. }
  721. FileName.Insert(L"%00", P);
  722. }
  723. }
  724. return FileName;
  725. }
  726. //---------------------------------------------------------------------------
  727. void __fastcall SplitCommand(UnicodeString Command, UnicodeString &Program,
  728. UnicodeString & Params, UnicodeString & Dir)
  729. {
  730. Command = Command.Trim();
  731. Params = L"";
  732. Dir = L"";
  733. if (!Command.IsEmpty() && (Command[1] == L'\"'))
  734. {
  735. Command.Delete(1, 1);
  736. int P = Command.Pos(L'"');
  737. if (P)
  738. {
  739. Program = Command.SubString(1, P-1).Trim();
  740. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  741. }
  742. else
  743. {
  744. throw Exception(FMTLOAD(INVALID_SHELL_COMMAND, (L"\"" + Command)));
  745. }
  746. }
  747. else
  748. {
  749. int P = Command.Pos(L" ");
  750. if (P)
  751. {
  752. Program = Command.SubString(1, P).Trim();
  753. Params = Command.SubString(P + 1, Command.Length() - P).Trim();
  754. }
  755. else
  756. {
  757. Program = Command;
  758. }
  759. }
  760. int B = Program.LastDelimiter(L"\\/");
  761. if (B)
  762. {
  763. Dir = Program.SubString(1, B).Trim();
  764. }
  765. }
  766. //---------------------------------------------------------------------------
  767. UnicodeString __fastcall ExtractProgram(UnicodeString Command)
  768. {
  769. UnicodeString Program;
  770. UnicodeString Params;
  771. UnicodeString Dir;
  772. SplitCommand(Command, Program, Params, Dir);
  773. return Program;
  774. }
  775. //---------------------------------------------------------------------------
  776. UnicodeString __fastcall ExtractProgramName(UnicodeString Command)
  777. {
  778. UnicodeString Name = ExtractFileName(ExtractProgram(Command));
  779. int Dot = Name.LastDelimiter(L".");
  780. if (Dot > 0)
  781. {
  782. Name = Name.SubString(1, Dot - 1);
  783. }
  784. return Name;
  785. }
  786. //---------------------------------------------------------------------------
  787. UnicodeString __fastcall FormatCommand(UnicodeString Program, UnicodeString Params)
  788. {
  789. Program = Program.Trim();
  790. Params = Params.Trim();
  791. if (!Params.IsEmpty()) Params = L" " + Params;
  792. Program = AddQuotes(Program);
  793. return Program + Params;
  794. }
  795. //---------------------------------------------------------------------------
  796. const wchar_t ShellCommandFileNamePattern[] = L"!.!";
  797. //---------------------------------------------------------------------------
  798. void __fastcall ReformatFileNameCommand(UnicodeString & Command)
  799. {
  800. if (!Command.IsEmpty())
  801. {
  802. UnicodeString Program, Params, Dir;
  803. SplitCommand(Command, Program, Params, Dir);
  804. if (Params.Pos(ShellCommandFileNamePattern) == 0)
  805. {
  806. Params = Params + (Params.IsEmpty() ? L"" : L" ") + ShellCommandFileNamePattern;
  807. }
  808. Command = FormatCommand(Program, Params);
  809. }
  810. }
  811. //---------------------------------------------------------------------------
  812. UnicodeString __fastcall ExpandFileNameCommand(const UnicodeString Command,
  813. const UnicodeString FileName)
  814. {
  815. return AnsiReplaceStr(Command, ShellCommandFileNamePattern,
  816. AddPathQuotes(FileName));
  817. }
  818. //---------------------------------------------------------------------------
  819. UnicodeString __fastcall EscapeParam(const UnicodeString & Param)
  820. {
  821. // Make sure this won't break RTF syntax
  822. return ReplaceStr(Param, L"\"", L"\"\"");
  823. }
  824. //---------------------------------------------------------------------------
  825. UnicodeString __fastcall EscapePuttyCommandParam(UnicodeString Param)
  826. {
  827. bool Space = false;
  828. for (int i = 1; i <= Param.Length(); i++)
  829. {
  830. switch (Param[i])
  831. {
  832. case L'"':
  833. Param.Insert(L"\\", i);
  834. i++;
  835. break;
  836. case L' ':
  837. Space = true;
  838. break;
  839. case L'\\':
  840. int i2 = i;
  841. while ((i2 <= Param.Length()) && (Param[i2] == L'\\'))
  842. {
  843. i2++;
  844. }
  845. if ((i2 <= Param.Length()) && (Param[i2] == L'"'))
  846. {
  847. while (Param[i] == L'\\')
  848. {
  849. Param.Insert(L"\\", i);
  850. i += 2;
  851. }
  852. i--;
  853. }
  854. break;
  855. }
  856. }
  857. if (Space)
  858. {
  859. Param = L"\"" + Param + L'"';
  860. }
  861. return Param;
  862. }
  863. //---------------------------------------------------------------------------
  864. UnicodeString __fastcall StringsToParams(TStrings * Strings)
  865. {
  866. UnicodeString Result;
  867. for (int Index = 0; Index < Strings->Count; Index++)
  868. {
  869. UnicodeString Name = Strings->Names[Index];
  870. UnicodeString Value = Strings->ValueFromIndex[Index];
  871. // Do not quote if it is all-numeric
  872. if (IntToStr(StrToIntDef(Value, -1)) != Value)
  873. {
  874. Value = FORMAT(L"\"%s\"", (EscapeParam(Value)));
  875. }
  876. Result += FORMAT(L" %s=%s", (Name, Value));
  877. }
  878. return Result;
  879. }
  880. //---------------------------------------------------------------------------
  881. UnicodeString __fastcall ExpandEnvironmentVariables(const UnicodeString & Str)
  882. {
  883. UnicodeString Buf;
  884. unsigned int Size = 1024;
  885. Buf.SetLength(Size);
  886. Buf.Unique();
  887. unsigned int Len = ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Size);
  888. if (Len > Size)
  889. {
  890. Buf.SetLength(Len);
  891. Buf.Unique();
  892. ExpandEnvironmentStrings(Str.c_str(), Buf.c_str(), Len);
  893. }
  894. PackStr(Buf);
  895. return Buf;
  896. }
  897. //---------------------------------------------------------------------------
  898. UnicodeString GetNormalizedPath(const UnicodeString & Path)
  899. {
  900. UnicodeString Result = ExcludeTrailingBackslash(Path);
  901. Result = FromUnixPath(Result);
  902. return Result;
  903. }
  904. //---------------------------------------------------------------------------
  905. UnicodeString GetCanonicalPath(const UnicodeString & Path)
  906. {
  907. UnicodeString Result = ExtractShortPathName(Path);
  908. if (Result.IsEmpty())
  909. {
  910. Result = Path;
  911. }
  912. Result = GetNormalizedPath(Result);
  913. return Result;
  914. }
  915. //---------------------------------------------------------------------------
  916. bool __fastcall IsPathToSameFile(const UnicodeString & Path1, const UnicodeString & Path2)
  917. {
  918. UnicodeString CanonicalPath1 = GetCanonicalPath(Path1);
  919. UnicodeString CanonicalPath2 = GetCanonicalPath(Path2);
  920. bool Result = SameText(CanonicalPath1, CanonicalPath2);
  921. return Result;
  922. }
  923. //---------------------------------------------------------------------------
  924. bool __fastcall SamePaths(const UnicodeString & Path1, const UnicodeString & Path2)
  925. {
  926. // TODO: ExpandUNCFileName
  927. return AnsiSameText(IncludeTrailingBackslash(Path1), IncludeTrailingBackslash(Path2));
  928. }
  929. //---------------------------------------------------------------------------
  930. int __fastcall CompareLogicalText(
  931. const UnicodeString & S1, const UnicodeString & S2, bool NaturalOrderNumericalSorting)
  932. {
  933. // Keep in sync with CompareLogicalTextPas
  934. int Result;
  935. if (NaturalOrderNumericalSorting)
  936. {
  937. Result = StrCmpLogicalW(S1.c_str(), S2.c_str());
  938. }
  939. else
  940. {
  941. Result = lstrcmpi(S1.c_str(), S2.c_str());
  942. }
  943. // For deterministics results
  944. if (Result == 0)
  945. {
  946. Result = lstrcmp(S1.c_str(), S2.c_str());
  947. }
  948. return Result;
  949. }
  950. //---------------------------------------------------------------------------
  951. int __fastcall CompareNumber(__int64 Value1, __int64 Value2)
  952. {
  953. int Result;
  954. if (Value1 < Value2)
  955. {
  956. Result = -1;
  957. }
  958. else if (Value1 == Value2)
  959. {
  960. Result = 0;
  961. }
  962. else
  963. {
  964. Result = 1;
  965. }
  966. return Result;
  967. }
  968. //---------------------------------------------------------------------------
  969. bool ContainsTextSemiCaseSensitive(const UnicodeString & Text, const UnicodeString & SubText)
  970. {
  971. bool Result;
  972. if (AnsiLowerCase(SubText) == SubText)
  973. {
  974. Result = ContainsText(Text, SubText);
  975. }
  976. else
  977. {
  978. Result = ContainsStr(Text, SubText);
  979. }
  980. return Result;
  981. }
  982. //---------------------------------------------------------------------------
  983. bool __fastcall IsReservedName(UnicodeString FileName)
  984. {
  985. int P = FileName.Pos(L".");
  986. int Len = (P > 0) ? P - 1 : FileName.Length();
  987. if ((Len == 3) || (Len == 4))
  988. {
  989. if (P > 0)
  990. {
  991. FileName.SetLength(P - 1);
  992. }
  993. static UnicodeString Reserved[] = {
  994. L"CON", L"PRN", L"AUX", L"NUL",
  995. L"COM1", L"COM2", L"COM3", L"COM4", L"COM5", L"COM6", L"COM7", L"COM8", L"COM9",
  996. L"LPT1", L"LPT2", L"LPT3", L"LPT4", L"LPT5", L"LPT6", L"LPT7", L"LPT8", L"LPT9" };
  997. for (unsigned int Index = 0; Index < LENOF(Reserved); Index++)
  998. {
  999. if (SameText(FileName, Reserved[Index]))
  1000. {
  1001. return true;
  1002. }
  1003. }
  1004. }
  1005. return false;
  1006. }
  1007. //---------------------------------------------------------------------------
  1008. // ApiPath support functions
  1009. // Inspired by
  1010. // https://stackoverflow.com/q/18580945/850848
  1011. // This can be reimplemented using PathCchCanonicalizeEx on Windows 8 and later
  1012. enum PATH_PREFIX_TYPE
  1013. {
  1014. PPT_UNKNOWN,
  1015. PPT_ABSOLUTE, //Found absolute path that is none of the other types
  1016. PPT_UNC, //Found \\server\share\ prefix
  1017. PPT_LONG_UNICODE, //Found \\?\ prefix
  1018. PPT_LONG_UNICODE_UNC, //Found \\?\UNC\ prefix
  1019. };
  1020. //---------------------------------------------------------------------------
  1021. static int __fastcall PathRootLength(UnicodeString Path)
  1022. {
  1023. // Correction for PathSkipRoot API
  1024. // Replace all /'s with \'s because PathSkipRoot can't handle /'s
  1025. UnicodeString Result = ReplaceChar(Path, L'/', L'\\');
  1026. // Now call the API
  1027. LPCTSTR Buffer = PathSkipRoot(Result.c_str());
  1028. return (Buffer != NULL) ? (Buffer - Result.c_str()) : -1;
  1029. }
  1030. //---------------------------------------------------------------------------
  1031. static bool __fastcall PathIsRelative_CorrectedForMicrosoftStupidity(UnicodeString Path)
  1032. {
  1033. // Correction for PathIsRelative API
  1034. // Replace all /'s with \'s because PathIsRelative can't handle /'s
  1035. UnicodeString Result = ReplaceChar(Path, L'/', L'\\');
  1036. //Now call the API
  1037. return PathIsRelative(Result.c_str());
  1038. }
  1039. //---------------------------------------------------------------------------
  1040. static int __fastcall GetOffsetAfterPathRoot(UnicodeString Path, PATH_PREFIX_TYPE & PrefixType)
  1041. {
  1042. // Checks if 'pPath' begins with the drive, share, prefix, etc
  1043. // EXAMPLES:
  1044. // Path Return: Points at: PrefixType:
  1045. // Relative\Folder\File.txt 0 Relative\Folder\File.txt PPT_UNKNOWN
  1046. // \RelativeToRoot\Folder 1 RelativeToRoot\Folder PPT_ABSOLUTE
  1047. // C:\Windows\Folder 3 Windows\Folder PPT_ABSOLUTE
  1048. // \\server\share\Desktop 15 Desktop PPT_UNC
  1049. // \\?\C:\Windows\Folder 7 Windows\Folder PPT_LONG_UNICODE
  1050. // \\?\UNC\server\share\Desktop 21 Desktop PPT_LONG_UNICODE_UNC
  1051. // RETURN:
  1052. // = Index in 'pPath' after the root, or
  1053. // = 0 if no root was found
  1054. int Result = 0;
  1055. PrefixType = PPT_UNKNOWN;
  1056. if (!Path.IsEmpty())
  1057. {
  1058. int Len = Path.Length();
  1059. bool WinXPOnly = !IsWinVista();
  1060. // The PathSkipRoot() API doesn't work correctly on Windows XP
  1061. if (!WinXPOnly)
  1062. {
  1063. // Works since Vista and up, but still needs correction :)
  1064. int RootLength = PathRootLength(Path);
  1065. if (RootLength >= 0)
  1066. {
  1067. Result = RootLength + 1;
  1068. }
  1069. }
  1070. // Now determine the type of prefix
  1071. int IndCheckUNC = -1;
  1072. if ((Len >= 8) &&
  1073. (Path[1] == L'\\' || Path[1] == L'/') &&
  1074. (Path[2] == L'\\' || Path[2] == L'/') &&
  1075. (Path[3] == L'?') &&
  1076. (Path[4] == L'\\' || Path[4] == L'/') &&
  1077. (Path[5] == L'U' || Path[5] == L'u') &&
  1078. (Path[6] == L'N' || Path[6] == L'n') &&
  1079. (Path[7] == L'C' || Path[7] == L'c') &&
  1080. (Path[8] == L'\\' || Path[8] == L'/'))
  1081. {
  1082. // Found \\?\UNC\ prefix
  1083. PrefixType = PPT_LONG_UNICODE_UNC;
  1084. if (WinXPOnly)
  1085. {
  1086. //For older OS
  1087. Result += 8;
  1088. }
  1089. //Check for UNC share later
  1090. IndCheckUNC = 8;
  1091. }
  1092. else if ((Len >= 4) &&
  1093. (Path[1] == L'\\' || Path[1] == L'/') &&
  1094. (Path[2] == L'\\' || Path[2] == L'/') &&
  1095. (Path[3] == L'?') &&
  1096. (Path[4] == L'\\' || Path[4] == L'/'))
  1097. {
  1098. // Found \\?\ prefix
  1099. PrefixType = PPT_LONG_UNICODE;
  1100. if (WinXPOnly)
  1101. {
  1102. //For older OS
  1103. Result += 4;
  1104. }
  1105. }
  1106. else if ((Len >= 2) &&
  1107. (Path[1] == L'\\' || Path[1] == L'/') &&
  1108. (Path[2] == L'\\' || Path[2] == L'/'))
  1109. {
  1110. // Check for UNC share later
  1111. IndCheckUNC = 2;
  1112. }
  1113. if (IndCheckUNC >= 0)
  1114. {
  1115. // Check for UNC, i.e. \\server\share\ part
  1116. int Index = IndCheckUNC;
  1117. for (int SkipSlashes = 2; SkipSlashes > 0; SkipSlashes--)
  1118. {
  1119. for(; Index <= Len; Index++)
  1120. {
  1121. TCHAR z = Path[Index];
  1122. if ((z == L'\\') || (z == L'/') || (Index >= Len))
  1123. {
  1124. Index++;
  1125. if (SkipSlashes == 1)
  1126. {
  1127. if (PrefixType == PPT_UNKNOWN)
  1128. {
  1129. PrefixType = PPT_UNC;
  1130. }
  1131. if (WinXPOnly)
  1132. {
  1133. //For older OS
  1134. Result = Index;
  1135. }
  1136. }
  1137. break;
  1138. }
  1139. }
  1140. }
  1141. }
  1142. if (WinXPOnly)
  1143. {
  1144. // Only if we didn't determine any other type
  1145. if (PrefixType == PPT_UNKNOWN)
  1146. {
  1147. if (!PathIsRelative_CorrectedForMicrosoftStupidity(Path.SubString(Result, Path.Length() - Result + 1)))
  1148. {
  1149. PrefixType = PPT_ABSOLUTE;
  1150. }
  1151. }
  1152. // For older OS only
  1153. int RootLength = PathRootLength(Path.SubString(Result, Path.Length() - Result + 1));
  1154. if (RootLength >= 0)
  1155. {
  1156. Result = RootLength + 1;
  1157. }
  1158. }
  1159. else
  1160. {
  1161. // Only if we didn't determine any other type
  1162. if (PrefixType == PPT_UNKNOWN)
  1163. {
  1164. if (!PathIsRelative_CorrectedForMicrosoftStupidity(Path))
  1165. {
  1166. PrefixType = PPT_ABSOLUTE;
  1167. }
  1168. }
  1169. }
  1170. }
  1171. return Result;
  1172. }
  1173. //---------------------------------------------------------------------------
  1174. UnicodeString __fastcall MakeUnicodeLargePath(UnicodeString Path)
  1175. {
  1176. // Convert path from 'into a larger Unicode path, that allows up to 32,767 character length
  1177. UnicodeString Result;
  1178. if (!Path.IsEmpty())
  1179. {
  1180. // Determine the type of the existing prefix
  1181. PATH_PREFIX_TYPE PrefixType;
  1182. GetOffsetAfterPathRoot(Path, PrefixType);
  1183. // Assume path to be without change
  1184. Result = Path;
  1185. switch (PrefixType)
  1186. {
  1187. case PPT_ABSOLUTE:
  1188. {
  1189. // First we need to check if its an absolute path relative to the root
  1190. bool AddPrefix = true;
  1191. if ((Path.Length() >= 1) &&
  1192. ((Path[1] == L'\\') || (Path[1] == L'/')))
  1193. {
  1194. AddPrefix = FALSE;
  1195. // Get current root path
  1196. UnicodeString CurrentDir = GetCurrentDir();
  1197. PATH_PREFIX_TYPE PrefixType2; // unused
  1198. int Following = GetOffsetAfterPathRoot(CurrentDir, PrefixType2);
  1199. if (Following > 0)
  1200. {
  1201. AddPrefix = true;
  1202. Result = CurrentDir.SubString(1, Following - 1) + Result.SubString(2, Result.Length() - 1);
  1203. }
  1204. }
  1205. if (AddPrefix)
  1206. {
  1207. // Add \\?\ prefix
  1208. Result = L"\\\\?\\" + Result;
  1209. }
  1210. }
  1211. break;
  1212. case PPT_UNC:
  1213. // First we need to remove the opening slashes for UNC share
  1214. if ((Result.Length() >= 2) &&
  1215. ((Result[1] == L'\\') || (Result[1] == L'/')) &&
  1216. ((Result[2] == L'\\') || (Result[2] == L'/')))
  1217. {
  1218. Result = Result.SubString(3, Result.Length() - 2);
  1219. }
  1220. // Add \\?\UNC\ prefix
  1221. Result = L"\\\\?\\UNC\\" + Result;
  1222. break;
  1223. case PPT_LONG_UNICODE:
  1224. case PPT_LONG_UNICODE_UNC:
  1225. // nothing to do
  1226. break;
  1227. }
  1228. }
  1229. return Result;
  1230. }
  1231. //---------------------------------------------------------------------------
  1232. UnicodeString __fastcall ApiPath(UnicodeString Path)
  1233. {
  1234. UnicodeString Drive = ExtractFileDrive(Path);
  1235. // This may match even a path like "C:" or "\\server\\share", but we do not really care
  1236. if (Drive.IsEmpty() || (Path.SubString(Drive.Length() + 1, 1) != L"\\"))
  1237. {
  1238. Path = ExpandFileName(Path);
  1239. }
  1240. // Max path for directories is 12 characters shorter than max path for files
  1241. if (Path.Length() >= MAX_PATH - 12)
  1242. {
  1243. if (Configuration != NULL)
  1244. {
  1245. Configuration->Usage->Inc(L"LongPath");
  1246. }
  1247. Path = MakeUnicodeLargePath(Path);
  1248. }
  1249. return Path;
  1250. }
  1251. //---------------------------------------------------------------------------
  1252. UnicodeString __fastcall DisplayableStr(const RawByteString & Str)
  1253. {
  1254. bool Displayable = true;
  1255. int Index = 1;
  1256. while ((Index <= Str.Length()) && Displayable)
  1257. {
  1258. if (((Str[Index] < '\x20') || (static_cast<unsigned char>(Str[Index]) >= static_cast<unsigned char>('\x80'))) &&
  1259. (Str[Index] != '\n') && (Str[Index] != '\r') && (Str[Index] != '\t') && (Str[Index] != '\b'))
  1260. {
  1261. Displayable = false;
  1262. }
  1263. Index++;
  1264. }
  1265. UnicodeString Result;
  1266. if (Displayable)
  1267. {
  1268. Result = L"\"";
  1269. for (int Index = 1; Index <= Str.Length(); Index++)
  1270. {
  1271. switch (Str[Index])
  1272. {
  1273. case '\n':
  1274. Result += L"\\n";
  1275. break;
  1276. case '\r':
  1277. Result += L"\\r";
  1278. break;
  1279. case '\t':
  1280. Result += L"\\t";
  1281. break;
  1282. case '\b':
  1283. Result += L"\\b";
  1284. break;
  1285. case '\\':
  1286. Result += L"\\\\";
  1287. break;
  1288. case '"':
  1289. Result += L"\\\"";
  1290. break;
  1291. default:
  1292. Result += wchar_t(Str[Index]);
  1293. break;
  1294. }
  1295. }
  1296. Result += L"\"";
  1297. }
  1298. else
  1299. {
  1300. Result = L"0x" + BytesToHex(Str);
  1301. }
  1302. return Result;
  1303. }
  1304. //---------------------------------------------------------------------------
  1305. UnicodeString __fastcall ByteToHex(unsigned char B, bool UpperCase)
  1306. {
  1307. static wchar_t UpperDigits[] = L"0123456789ABCDEF";
  1308. static wchar_t LowerDigits[] = L"0123456789abcdef";
  1309. const wchar_t * Digits = (UpperCase ? UpperDigits : LowerDigits);
  1310. UnicodeString Result;
  1311. Result.SetLength(2);
  1312. Result[1] = Digits[(B & 0xF0) >> 4];
  1313. Result[2] = Digits[(B & 0x0F) >> 0];
  1314. return Result;
  1315. }
  1316. //---------------------------------------------------------------------------
  1317. UnicodeString __fastcall BytesToHex(const unsigned char * B, size_t Length, bool UpperCase, wchar_t Separator)
  1318. {
  1319. UnicodeString Result;
  1320. for (size_t i = 0; i < Length; i++)
  1321. {
  1322. Result += ByteToHex(B[i], UpperCase);
  1323. if ((Separator != L'\0') && (i < Length - 1))
  1324. {
  1325. Result += Separator;
  1326. }
  1327. }
  1328. return Result;
  1329. }
  1330. //---------------------------------------------------------------------------
  1331. UnicodeString __fastcall BytesToHex(RawByteString Str, bool UpperCase, wchar_t Separator)
  1332. {
  1333. return BytesToHex(reinterpret_cast<const unsigned char *>(Str.c_str()), Str.Length(), UpperCase, Separator);
  1334. }
  1335. //---------------------------------------------------------------------------
  1336. UnicodeString __fastcall CharToHex(wchar_t Ch, bool UpperCase)
  1337. {
  1338. return BytesToHex(reinterpret_cast<const unsigned char *>(&Ch), sizeof(Ch), UpperCase);
  1339. }
  1340. //---------------------------------------------------------------------------
  1341. RawByteString __fastcall HexToBytes(const UnicodeString Hex)
  1342. {
  1343. static UnicodeString Digits = L"0123456789ABCDEF";
  1344. RawByteString Result;
  1345. int L, P1, P2;
  1346. L = Hex.Length();
  1347. if (L % 2 == 0)
  1348. {
  1349. for (int i = 1; i <= Hex.Length(); i += 2)
  1350. {
  1351. P1 = Digits.Pos(towupper(Hex[i]));
  1352. P2 = Digits.Pos(towupper(Hex[i + 1]));
  1353. if (P1 <= 0 || P2 <= 0)
  1354. {
  1355. Result = L"";
  1356. break;
  1357. }
  1358. else
  1359. {
  1360. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  1361. }
  1362. }
  1363. }
  1364. return Result;
  1365. }
  1366. //---------------------------------------------------------------------------
  1367. unsigned char __fastcall HexToByte(const UnicodeString Hex)
  1368. {
  1369. static UnicodeString Digits = L"0123456789ABCDEF";
  1370. DebugAssert(Hex.Length() == 2);
  1371. int P1 = Digits.Pos(towupper(Hex[1]));
  1372. int P2 = Digits.Pos(towupper(Hex[2]));
  1373. return
  1374. static_cast<unsigned char>(((P1 <= 0) || (P2 <= 0)) ? 0 : (((P1 - 1) << 4) + (P2 - 1)));
  1375. }
  1376. //---------------------------------------------------------------------------
  1377. bool __fastcall IsLowerCaseLetter(wchar_t Ch)
  1378. {
  1379. return (Ch >= 'a') && (Ch <= 'z');
  1380. }
  1381. //---------------------------------------------------------------------------
  1382. bool __fastcall IsUpperCaseLetter(wchar_t Ch)
  1383. {
  1384. return (Ch >= 'A') && (Ch <= 'Z');
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. bool __fastcall IsLetter(wchar_t Ch)
  1388. {
  1389. return IsLowerCaseLetter(Ch) || IsUpperCaseLetter(Ch);
  1390. }
  1391. //---------------------------------------------------------------------------
  1392. bool __fastcall IsDigit(wchar_t Ch)
  1393. {
  1394. return (Ch >= '0') && (Ch <= '9');
  1395. }
  1396. //---------------------------------------------------------------------------
  1397. bool __fastcall IsHex(wchar_t Ch)
  1398. {
  1399. return
  1400. IsDigit(Ch) ||
  1401. ((Ch >= 'A') && (Ch <= 'F')) ||
  1402. ((Ch >= 'a') && (Ch <= 'f'));
  1403. }
  1404. //---------------------------------------------------------------------------
  1405. TSearchRecSmart::TSearchRecSmart()
  1406. {
  1407. FLastWriteTimeSource.dwLowDateTime = 0;
  1408. FLastWriteTimeSource.dwHighDateTime = 0;
  1409. }
  1410. //---------------------------------------------------------------------------
  1411. void TSearchRecSmart::Clear()
  1412. {
  1413. Size = 0;
  1414. Attr = 0;
  1415. Name = TFileName();
  1416. ExcludeAttr = 0;
  1417. FindHandle = 0;
  1418. memset(&FindData, 0, sizeof(FindData));
  1419. FLastWriteTimeSource.dwLowDateTime = 0;
  1420. FLastWriteTimeSource.dwHighDateTime = 0;
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. TDateTime TSearchRecSmart::GetLastWriteTime() const
  1424. {
  1425. if ((FindData.ftLastWriteTime.dwLowDateTime != FLastWriteTimeSource.dwLowDateTime) ||
  1426. (FindData.ftLastWriteTime.dwHighDateTime != FLastWriteTimeSource.dwHighDateTime))
  1427. {
  1428. FLastWriteTimeSource = FindData.ftLastWriteTime;
  1429. FLastWriteTime = FileTimeToDateTime(FLastWriteTimeSource);
  1430. }
  1431. return FLastWriteTime;
  1432. }
  1433. //---------------------------------------------------------------------------
  1434. bool TSearchRecSmart::IsRealFile() const
  1435. {
  1436. return ::IsRealFile(Name);
  1437. }
  1438. //---------------------------------------------------------------------------
  1439. bool TSearchRecSmart::IsDirectory() const
  1440. {
  1441. return FLAGSET(Attr, faDirectory);
  1442. }
  1443. //---------------------------------------------------------------------------
  1444. bool TSearchRecSmart::IsHidden() const
  1445. {
  1446. return FLAGSET(Attr, faHidden);
  1447. }
  1448. //---------------------------------------------------------------------------
  1449. UnicodeString TSearchRecChecked::GetFilePath() const
  1450. {
  1451. return TPath::Combine(Dir, Name);
  1452. }
  1453. //---------------------------------------------------------------------------
  1454. TSearchRecOwned::~TSearchRecOwned()
  1455. {
  1456. if (Opened)
  1457. {
  1458. FindClose(*this);
  1459. }
  1460. }
  1461. //---------------------------------------------------------------------------
  1462. void TSearchRecOwned::Close()
  1463. {
  1464. FindClose(*this);
  1465. Opened = false;
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. int __fastcall FindCheck(int Result, const UnicodeString & Path)
  1469. {
  1470. if ((Result != ERROR_SUCCESS) &&
  1471. (Result != ERROR_FILE_NOT_FOUND) &&
  1472. (Result != ERROR_NO_MORE_FILES))
  1473. {
  1474. throw EOSExtException(FMTLOAD(FIND_FILE_ERROR, (Path)), Result);
  1475. }
  1476. return Result;
  1477. }
  1478. //---------------------------------------------------------------------------
  1479. int __fastcall FindFirstUnchecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1480. {
  1481. F.Path = Path;
  1482. F.Dir = ExtractFilePath(Path);
  1483. int Result = FindFirst(ApiPath(Path), Attr, F);
  1484. F.Opened = (Result == 0);
  1485. return Result;
  1486. }
  1487. //---------------------------------------------------------------------------
  1488. int __fastcall FindFirstChecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1489. {
  1490. int Result = FindFirstUnchecked(Path, Attr, F);
  1491. return FindCheck(Result, F.Path);
  1492. }
  1493. //---------------------------------------------------------------------------
  1494. // Equivalent to FindNext, just to complement to FindFirstUnchecked
  1495. int __fastcall FindNextUnchecked(TSearchRecChecked & F)
  1496. {
  1497. return FindNext(F);
  1498. }
  1499. //---------------------------------------------------------------------------
  1500. // It can make sense to use FindNextChecked, even if unchecked FindFirst is used.
  1501. // I.e. even if we do not care that FindFirst failed, if FindNext
  1502. // fails after successful FindFirst, it means some terrible problem
  1503. int __fastcall FindNextChecked(TSearchRecChecked & F)
  1504. {
  1505. return FindCheck(FindNextUnchecked(F), F.Path);
  1506. }
  1507. //---------------------------------------------------------------------------
  1508. bool __fastcall FileSearchRec(const UnicodeString FileName, TSearchRec & Rec)
  1509. {
  1510. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1511. bool Result = (FindFirst(ApiPath(FileName), FindAttrs, Rec) == 0);
  1512. if (Result)
  1513. {
  1514. FindClose(Rec);
  1515. }
  1516. return Result;
  1517. }
  1518. //---------------------------------------------------------------------------
  1519. void CopySearchRec(const TSearchRec & Source, TSearchRec & Dest)
  1520. {
  1521. // Strangely issues a compiler warning (W8111 due to TSearchRec::Time), when used in Script.cpp, but not here.
  1522. Dest = Source;
  1523. }
  1524. //---------------------------------------------------------------------------
  1525. bool __fastcall IsRealFile(const UnicodeString & FileName)
  1526. {
  1527. return (FileName != THISDIRECTORY) && (FileName != PARENTDIRECTORY);
  1528. }
  1529. //---------------------------------------------------------------------------
  1530. UnicodeString GetOSInfo()
  1531. {
  1532. UnicodeString Result = WindowsVersionLong();
  1533. AddToList(Result, WindowsProductName(), TitleSeparator);
  1534. return Result;
  1535. }
  1536. //---------------------------------------------------------------------------
  1537. UnicodeString GetEnvironmentInfo()
  1538. {
  1539. UnicodeString Result = FORMAT(L"WinSCP %s (OS %s)", (Configuration->VersionStr, GetOSInfo()));
  1540. return Result;
  1541. }
  1542. //---------------------------------------------------------------------------
  1543. void __fastcall ProcessLocalDirectory(UnicodeString DirName,
  1544. TProcessLocalFileEvent CallBackFunc, void * Param,
  1545. int FindAttrs)
  1546. {
  1547. DebugAssert(CallBackFunc);
  1548. if (FindAttrs < 0)
  1549. {
  1550. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1551. }
  1552. TSearchRecOwned SearchRec;
  1553. if (FindFirstChecked(TPath::Combine(DirName, AnyMask), FindAttrs, SearchRec) == 0)
  1554. {
  1555. do
  1556. {
  1557. if (SearchRec.IsRealFile())
  1558. {
  1559. CallBackFunc(SearchRec.GetFilePath(), SearchRec, Param);
  1560. }
  1561. } while (FindNextChecked(SearchRec) == 0);
  1562. }
  1563. }
  1564. //---------------------------------------------------------------------------
  1565. int __fastcall FileGetAttrFix(const UnicodeString & FileName)
  1566. {
  1567. // Already called with ApiPath
  1568. int Result;
  1569. int Tries = 2;
  1570. do
  1571. {
  1572. // WORKAROUND:
  1573. // FileGetAttr when called for link with FollowLink set (default) will always fail on pre-Vista
  1574. // as it calls InternalGetFileNameFromSymLink, which test for CheckWin32Version(6, 0)
  1575. Result = GetFileAttributes(FileName.c_str());
  1576. if ((Result >= 0) && FLAGSET(Result, faSymLink) && IsWinVista())
  1577. {
  1578. try
  1579. {
  1580. UnicodeString TargetName;
  1581. // WORKAROUND:
  1582. // On Samba, InternalGetFileNameFromSymLink fails and returns true but empty target.
  1583. // That confuses FileGetAttr, which returns attributes of the parent folder instead.
  1584. // Using FileGetSymLinkTarget solves the problem, as it returns false.
  1585. if (!FileGetSymLinkTarget(FileName, TargetName))
  1586. {
  1587. // FileGetAttr would return faInvalid (-1), but we want to allow an upload from Samba,
  1588. // so returning the symlink attributes => noop
  1589. }
  1590. else
  1591. {
  1592. Result = GetFileAttributes(ApiPath(TargetName).c_str());
  1593. }
  1594. }
  1595. catch (EOSError & E)
  1596. {
  1597. Result = -1;
  1598. }
  1599. catch (EDirectoryNotFoundException & E) // throws by FileSystemAttributes
  1600. {
  1601. Result = -1;
  1602. }
  1603. }
  1604. Tries--;
  1605. }
  1606. // When referring to files in some special symlinked locations
  1607. // (like a deduplicated drive or a commvault archive), the first call to FileGetAttr failed.
  1608. // Possibly this issue is resolved by our re-implementation of FileGetAttr above.
  1609. // But as we have no way to test it, keeping the retry here.
  1610. while ((Result < 0) && (Tries > 0));
  1611. return Result;
  1612. }
  1613. //---------------------------------------------------------------------------
  1614. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  1615. {
  1616. try
  1617. {
  1618. TDateTime DateTime = EncodeDate(Year, Month, Day);
  1619. return DateTime;
  1620. }
  1621. catch (EConvertError & E)
  1622. {
  1623. throw EConvertError(FORMAT(L"%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  1624. }
  1625. }
  1626. //---------------------------------------------------------------------------
  1627. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  1628. {
  1629. try
  1630. {
  1631. TDateTime DateTime = EncodeTime(Hour, Min, Sec, MSec);
  1632. return DateTime;
  1633. }
  1634. catch (EConvertError & E)
  1635. {
  1636. throw EConvertError(FORMAT(L"%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  1637. }
  1638. }
  1639. //---------------------------------------------------------------------------
  1640. TDateTime __fastcall SystemTimeToDateTimeVerbose(const SYSTEMTIME & SystemTime)
  1641. {
  1642. try
  1643. {
  1644. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1645. return DateTime;
  1646. }
  1647. catch (EConvertError & E)
  1648. {
  1649. throw EConvertError(FORMAT(L"%s [%d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d.%3.3d]", (E.Message, int(SystemTime.wYear), int(SystemTime.wMonth), int(SystemTime.wDay), int(SystemTime.wHour), int(SystemTime.wMinute), int(SystemTime.wSecond), int(SystemTime.wMilliseconds))));
  1650. }
  1651. }
  1652. //---------------------------------------------------------------------------
  1653. struct TDateTimeParams
  1654. {
  1655. TDateTime UnixEpoch;
  1656. double BaseDifference;
  1657. long BaseDifferenceSec;
  1658. // All Current* are actually global, not per-year and
  1659. // are valid for Year 0 (current) only
  1660. double CurrentDaylightDifference;
  1661. long CurrentDaylightDifferenceSec;
  1662. double CurrentDifference;
  1663. long CurrentDifferenceSec;
  1664. double StandardDifference;
  1665. long StandardDifferenceSec;
  1666. double DaylightDifference;
  1667. long DaylightDifferenceSec;
  1668. SYSTEMTIME SystemStandardDate;
  1669. SYSTEMTIME SystemDaylightDate;
  1670. TDateTime StandardDate;
  1671. TDateTime DaylightDate;
  1672. UnicodeString StandardName;
  1673. UnicodeString DaylightName;
  1674. // This is actually global, not per-year
  1675. bool DaylightHack;
  1676. bool HasDST() const
  1677. {
  1678. // On some systems it occurs that StandardDate is unset, while
  1679. // DaylightDate is set. MSDN states that this is invalid and
  1680. // should be treated as if there is no daylight saving.
  1681. // So check both.
  1682. return
  1683. (SystemStandardDate.wMonth != 0) &&
  1684. (SystemDaylightDate.wMonth != 0);
  1685. }
  1686. bool SummerDST() const
  1687. {
  1688. return HasDST() && (DaylightDate < StandardDate);
  1689. }
  1690. };
  1691. typedef std::map<int, TDateTimeParams> TYearlyDateTimeParams;
  1692. static TYearlyDateTimeParams YearlyDateTimeParams;
  1693. static std::unique_ptr<TCriticalSection> DateTimeParamsSection(TraceInitPtr(new TCriticalSection()));
  1694. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1695. TDateTime & Result);
  1696. //---------------------------------------------------------------------------
  1697. static unsigned short __fastcall DecodeYear(const TDateTime & DateTime)
  1698. {
  1699. unsigned short Year, Month, Day;
  1700. DecodeDate(DateTime, Year, Month, Day);
  1701. return Year;
  1702. }
  1703. //---------------------------------------------------------------------------
  1704. static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year)
  1705. {
  1706. TGuard Guard(DateTimeParamsSection.get());
  1707. TDateTimeParams * Result;
  1708. TYearlyDateTimeParams::iterator i = YearlyDateTimeParams.find(Year);
  1709. if (i != YearlyDateTimeParams.end())
  1710. {
  1711. Result = &(*i).second;
  1712. }
  1713. else
  1714. {
  1715. // creates new entry as a side effect
  1716. Result = &YearlyDateTimeParams[Year];
  1717. TIME_ZONE_INFORMATION TZI;
  1718. unsigned long GTZI;
  1719. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  1720. typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi);
  1721. TGetTimeZoneInformationForYear GetTimeZoneInformationForYear =
  1722. (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear");
  1723. if ((Year == 0) || (GetTimeZoneInformationForYear == NULL))
  1724. {
  1725. GTZI = GetTimeZoneInformation(&TZI);
  1726. }
  1727. else
  1728. {
  1729. GetTimeZoneInformationForYear(Year, NULL, &TZI);
  1730. GTZI = TIME_ZONE_ID_UNKNOWN;
  1731. }
  1732. switch (GTZI)
  1733. {
  1734. case TIME_ZONE_ID_UNKNOWN:
  1735. Result->CurrentDaylightDifferenceSec = 0;
  1736. break;
  1737. case TIME_ZONE_ID_STANDARD:
  1738. Result->CurrentDaylightDifferenceSec = TZI.StandardBias;
  1739. break;
  1740. case TIME_ZONE_ID_DAYLIGHT:
  1741. Result->CurrentDaylightDifferenceSec = TZI.DaylightBias;
  1742. break;
  1743. case TIME_ZONE_ID_INVALID:
  1744. default:
  1745. throw Exception(TIMEZONE_ERROR);
  1746. }
  1747. Result->BaseDifferenceSec = TZI.Bias;
  1748. Result->BaseDifference = double(TZI.Bias) / MinsPerDay;
  1749. Result->BaseDifferenceSec *= SecsPerMin;
  1750. Result->CurrentDifferenceSec = TZI.Bias +
  1751. Result->CurrentDaylightDifferenceSec;
  1752. Result->CurrentDifference =
  1753. double(Result->CurrentDifferenceSec) / MinsPerDay;
  1754. Result->CurrentDifferenceSec *= SecsPerMin;
  1755. Result->CurrentDaylightDifference =
  1756. double(Result->CurrentDaylightDifferenceSec) / MinsPerDay;
  1757. Result->CurrentDaylightDifferenceSec *= SecsPerMin;
  1758. Result->DaylightDifferenceSec = TZI.DaylightBias * SecsPerMin;
  1759. Result->DaylightDifference = double(TZI.DaylightBias) / MinsPerDay;
  1760. Result->StandardDifferenceSec = TZI.StandardBias * SecsPerMin;
  1761. Result->StandardDifference = double(TZI.StandardBias) / MinsPerDay;
  1762. Result->SystemStandardDate = TZI.StandardDate;
  1763. Result->SystemDaylightDate = TZI.DaylightDate;
  1764. unsigned short AYear = (Year != 0) ? Year : DecodeYear(Now());
  1765. if (Result->HasDST())
  1766. {
  1767. EncodeDSTMargin(Result->SystemStandardDate, AYear, Result->StandardDate);
  1768. EncodeDSTMargin(Result->SystemDaylightDate, AYear, Result->DaylightDate);
  1769. }
  1770. Result->StandardName = TZI.StandardName;
  1771. Result->DaylightName = TZI.DaylightName;
  1772. Result->DaylightHack = !IsWin7();
  1773. }
  1774. return Result;
  1775. }
  1776. //---------------------------------------------------------------------------
  1777. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1778. TDateTime & Result)
  1779. {
  1780. if (Date.wYear == 0)
  1781. {
  1782. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  1783. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  1784. (7 * (Date.wDay - 1));
  1785. // Day 5 means, the last occurence of day-of-week in month
  1786. if (Date.wDay == 5)
  1787. {
  1788. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  1789. if (Month > 12)
  1790. {
  1791. Month = static_cast<unsigned short>(Month - 12);
  1792. Year++;
  1793. }
  1794. if (Result >= EncodeDateVerbose(Year, Month, 1))
  1795. {
  1796. Result -= 7;
  1797. }
  1798. }
  1799. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  1800. Date.wMilliseconds);
  1801. }
  1802. else
  1803. {
  1804. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  1805. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  1806. }
  1807. }
  1808. //---------------------------------------------------------------------------
  1809. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  1810. {
  1811. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1812. bool Result;
  1813. // On some systems it occurs that StandardDate is unset, while
  1814. // DaylightDate is set. MSDN states that this is invalid and
  1815. // should be treated as if there is no daylight saving.
  1816. // So check both.
  1817. if (!Params->HasDST())
  1818. {
  1819. Result = false;
  1820. }
  1821. else
  1822. {
  1823. if (Params->SummerDST())
  1824. {
  1825. Result =
  1826. (DateTime >= Params->DaylightDate) &&
  1827. (DateTime < Params->StandardDate);
  1828. }
  1829. else
  1830. {
  1831. Result =
  1832. (DateTime < Params->StandardDate) ||
  1833. (DateTime >= Params->DaylightDate);
  1834. }
  1835. }
  1836. return Result;
  1837. }
  1838. //---------------------------------------------------------------------------
  1839. bool __fastcall UsesDaylightHack()
  1840. {
  1841. return GetDateTimeParams(0)->DaylightHack;
  1842. }
  1843. //---------------------------------------------------------------------------
  1844. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  1845. {
  1846. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1847. TDateTime Result = UnixDateDelta + (double(TimeStamp) / SecsPerDay);
  1848. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(Result));
  1849. if (Params->DaylightHack)
  1850. {
  1851. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1852. {
  1853. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1854. Result -= CurrentParams->CurrentDifference;
  1855. }
  1856. else if (DSTMode == dstmKeep)
  1857. {
  1858. Result -= Params->BaseDifference;
  1859. }
  1860. }
  1861. else
  1862. {
  1863. Result -= Params->BaseDifference;
  1864. }
  1865. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1866. {
  1867. Result -= DSTDifferenceForTime(Result);
  1868. }
  1869. return Result;
  1870. }
  1871. //---------------------------------------------------------------------------
  1872. __int64 __fastcall Round(double Number)
  1873. {
  1874. double Floor = floor(Number);
  1875. double Ceil = ceil(Number);
  1876. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1877. }
  1878. //---------------------------------------------------------------------------
  1879. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime, bool Add)
  1880. {
  1881. S = S.Trim();
  1882. int Index = 1;
  1883. if (SameText(S, L"today"))
  1884. {
  1885. S = L"0DS";
  1886. }
  1887. else if (SameText(S, L"yesterday"))
  1888. {
  1889. S = L"1DS";
  1890. }
  1891. while ((Index <= S.Length()) && IsDigit(S[Index]))
  1892. {
  1893. Index++;
  1894. }
  1895. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1896. int Number;
  1897. bool Result = TryStrToInt(NumberStr, Number);
  1898. if (Result)
  1899. {
  1900. if (!Add)
  1901. {
  1902. Number = -Number;
  1903. }
  1904. S.Delete(1, Index - 1);
  1905. S = S.Trim().UpperCase();
  1906. bool Start = (S.Length() == 2) && (S[2] == L'S');
  1907. if (Start)
  1908. {
  1909. S.SetLength(S.Length() - 1);
  1910. }
  1911. DateTime = Now();
  1912. // These may not overlap with ParseSize (K, M and G)
  1913. if (S == L"S")
  1914. {
  1915. DateTime = IncSecond(DateTime, Number);
  1916. if (Start)
  1917. {
  1918. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheSecond(DateTime)));
  1919. }
  1920. }
  1921. else if (S == L"N")
  1922. {
  1923. DateTime = IncMinute(DateTime, Number);
  1924. if (Start)
  1925. {
  1926. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheMinute(DateTime)));
  1927. }
  1928. }
  1929. else if (S == L"H")
  1930. {
  1931. DateTime = IncHour(DateTime, Number);
  1932. if (Start)
  1933. {
  1934. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheHour(DateTime)));
  1935. }
  1936. }
  1937. else if (S == L"D")
  1938. {
  1939. DateTime = IncDay(DateTime, Number);
  1940. if (Start)
  1941. {
  1942. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheDay(DateTime)));
  1943. }
  1944. }
  1945. else if (S == L"Y")
  1946. {
  1947. DateTime = IncYear(DateTime, Number);
  1948. if (Start)
  1949. {
  1950. DateTime = IncMilliSecond(DateTime, -MilliSecondOfTheYear(DateTime));
  1951. }
  1952. }
  1953. else
  1954. {
  1955. Result = false;
  1956. }
  1957. }
  1958. return Result;
  1959. }
  1960. //---------------------------------------------------------------------------
  1961. bool TryStrToDateTimeStandard(const UnicodeString & S, TDateTime & Value)
  1962. {
  1963. TFormatSettings FormatSettings = TFormatSettings::Create(GetDefaultLCID());
  1964. FormatSettings.DateSeparator = L'-';
  1965. FormatSettings.TimeSeparator = L':';
  1966. FormatSettings.ShortDateFormat = "yyyy/mm/dd";
  1967. FormatSettings.ShortTimeFormat = "hh:nn:ss";
  1968. return TryStrToDateTime(S, Value, FormatSettings);
  1969. }
  1970. //---------------------------------------------------------------------------
  1971. const wchar_t KiloSize = L'K';
  1972. const wchar_t MegaSize = L'M';
  1973. const wchar_t GigaSize = L'G';
  1974. //---------------------------------------------------------------------------
  1975. // Keep consistent with parse_blocksize
  1976. bool __fastcall TryStrToSize(UnicodeString SizeStr, __int64 & Size)
  1977. {
  1978. int Index = 0;
  1979. while ((Index + 1 <= SizeStr.Length()) && IsDigit(SizeStr[Index + 1]))
  1980. {
  1981. Index++;
  1982. }
  1983. bool Result =
  1984. (Index > 0) && TryStrToInt64(SizeStr.SubString(1, Index), Size);
  1985. if (Result)
  1986. {
  1987. SizeStr = SizeStr.SubString(Index + 1, SizeStr.Length() - Index).Trim();
  1988. if (!SizeStr.IsEmpty())
  1989. {
  1990. Result = (SizeStr.Length() == 1);
  1991. if (Result)
  1992. {
  1993. wchar_t Unit = towupper(SizeStr[1]);
  1994. switch (Unit)
  1995. {
  1996. case GigaSize:
  1997. Size *= 1024;
  1998. // fallthru
  1999. case MegaSize:
  2000. Size *= 1024;
  2001. // fallthru
  2002. case KiloSize:
  2003. Size *= 1024;
  2004. break;
  2005. default:
  2006. Result = false;
  2007. }
  2008. }
  2009. }
  2010. }
  2011. return Result;
  2012. }
  2013. //---------------------------------------------------------------------------
  2014. UnicodeString __fastcall SizeToStr(__int64 Size)
  2015. {
  2016. UnicodeString Result;
  2017. if ((Size <= 0) || ((Size % 1024) != 0))
  2018. {
  2019. Result = IntToStr(Size);
  2020. }
  2021. else
  2022. {
  2023. Size /= 1024;
  2024. if ((Size % 1024) != 0)
  2025. {
  2026. Result = IntToStr(Size) + KiloSize;
  2027. }
  2028. else
  2029. {
  2030. Size /= 1024;
  2031. if ((Size % 1024) != 0)
  2032. {
  2033. Result = IntToStr(Size) + MegaSize;
  2034. }
  2035. else
  2036. {
  2037. Size /= 1024;
  2038. Result = IntToStr(Size) + GigaSize;
  2039. }
  2040. }
  2041. }
  2042. return Result;
  2043. }
  2044. //---------------------------------------------------------------------------
  2045. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  2046. {
  2047. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2048. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  2049. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  2050. CurrentParams->CurrentDifferenceSec;
  2051. }
  2052. //---------------------------------------------------------------------------
  2053. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  2054. TDSTMode /*DSTMode*/)
  2055. {
  2056. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  2057. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2058. if (!Params->DaylightHack)
  2059. {
  2060. // We should probably use reversed code of FileTimeToDateTime here instead of custom implementation
  2061. // We are incrementing and decrementing BaseDifferenceSec because it
  2062. // can actually change between years
  2063. // (as it did in Belarus from GMT+2 to GMT+3 between 2011 and 2012)
  2064. UnixTimeStamp += (IsDateInDST(DateTime) ?
  2065. Params->DaylightDifferenceSec : Params->StandardDifferenceSec) +
  2066. Params->BaseDifferenceSec;
  2067. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2068. UnixTimeStamp -=
  2069. CurrentParams->CurrentDaylightDifferenceSec +
  2070. CurrentParams->BaseDifferenceSec;
  2071. }
  2072. FILETIME Result;
  2073. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  2074. return Result;
  2075. }
  2076. //---------------------------------------------------------------------------
  2077. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  2078. {
  2079. // duplicated in DirView.pas
  2080. TDateTime Result;
  2081. // The 0xFFF... is sometime seen for invalid timestamps,
  2082. // it would cause failure in SystemTimeToDateTime below
  2083. if (FileTime.dwLowDateTime == std::numeric_limits<DWORD>::max())
  2084. {
  2085. Result = MinDateTime;
  2086. }
  2087. else
  2088. {
  2089. SYSTEMTIME SysTime;
  2090. if (!UsesDaylightHack())
  2091. {
  2092. SYSTEMTIME UniverzalSysTime;
  2093. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  2094. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  2095. }
  2096. else
  2097. {
  2098. FILETIME LocalFileTime;
  2099. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  2100. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  2101. }
  2102. Result = SystemTimeToDateTimeVerbose(SysTime);
  2103. }
  2104. return Result;
  2105. }
  2106. //---------------------------------------------------------------------------
  2107. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  2108. TDSTMode DSTMode)
  2109. {
  2110. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  2111. if (UsesDaylightHack())
  2112. {
  2113. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  2114. {
  2115. FILETIME LocalFileTime;
  2116. SYSTEMTIME SystemTime;
  2117. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  2118. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  2119. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  2120. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2121. Result += (IsDateInDST(DateTime) ?
  2122. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  2123. if (DSTMode == dstmKeep)
  2124. {
  2125. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2126. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  2127. }
  2128. }
  2129. }
  2130. else
  2131. {
  2132. if (DSTMode == dstmWin)
  2133. {
  2134. FILETIME LocalFileTime;
  2135. SYSTEMTIME SystemTime;
  2136. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  2137. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  2138. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  2139. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2140. Result -= (IsDateInDST(DateTime) ?
  2141. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  2142. }
  2143. }
  2144. return Result;
  2145. }
  2146. //---------------------------------------------------------------------------
  2147. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  2148. {
  2149. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2150. DateTime += DSTDifferenceForTime(DateTime);
  2151. DateTime += Params->BaseDifference;
  2152. if (Params->DaylightHack)
  2153. {
  2154. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2155. DateTime += CurrentParams->CurrentDaylightDifference;
  2156. }
  2157. return DateTime;
  2158. }
  2159. //---------------------------------------------------------------------------
  2160. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  2161. {
  2162. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2163. DateTime -= DSTDifferenceForTime(DateTime);
  2164. DateTime -= Params->BaseDifference;
  2165. if (Params->DaylightHack)
  2166. {
  2167. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2168. DateTime -= CurrentParams->CurrentDaylightDifference;
  2169. }
  2170. return DateTime;
  2171. }
  2172. //---------------------------------------------------------------------------
  2173. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  2174. TDSTMode DSTMode)
  2175. {
  2176. __int64 Result;
  2177. if ((FileTime.dwLowDateTime == 0) &&
  2178. (FileTime.dwHighDateTime == 0))
  2179. {
  2180. Result = ::DateTimeToUnix(Now());
  2181. }
  2182. else
  2183. {
  2184. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  2185. }
  2186. return Result;
  2187. }
  2188. //---------------------------------------------------------------------------
  2189. double __fastcall DSTDifferenceForTime(TDateTime DateTime)
  2190. {
  2191. double Result;
  2192. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2193. if (IsDateInDST(DateTime))
  2194. {
  2195. Result = Params->DaylightDifference;
  2196. }
  2197. else
  2198. {
  2199. Result = Params->StandardDifference;
  2200. }
  2201. return Result;
  2202. }
  2203. //---------------------------------------------------------------------------
  2204. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  2205. {
  2206. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2207. if (Params->DaylightHack)
  2208. {
  2209. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  2210. {
  2211. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2212. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  2213. }
  2214. if (!IsDateInDST(DateTime))
  2215. {
  2216. if (DSTMode == dstmWin)
  2217. {
  2218. DateTime = DateTime - Params->DaylightDifference;
  2219. }
  2220. }
  2221. else
  2222. {
  2223. DateTime = DateTime - Params->StandardDifference;
  2224. }
  2225. }
  2226. else
  2227. {
  2228. if (DSTMode == dstmWin)
  2229. {
  2230. DateTime = DateTime + DSTDifferenceForTime(DateTime);
  2231. }
  2232. }
  2233. return DateTime;
  2234. }
  2235. //---------------------------------------------------------------------------
  2236. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  2237. {
  2238. UnicodeString Result = Format;
  2239. bool AsIs = false;
  2240. int Index = 1;
  2241. while (Index <= Result.Length())
  2242. {
  2243. wchar_t F = Result[Index];
  2244. if ((F == L'\'') || (F == L'\"'))
  2245. {
  2246. AsIs = !AsIs;
  2247. Index++;
  2248. }
  2249. else if (!AsIs && ((F == L'a') || (F == L'A')))
  2250. {
  2251. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  2252. {
  2253. Index += 5;
  2254. }
  2255. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  2256. {
  2257. Index += 3;
  2258. }
  2259. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  2260. {
  2261. Index += 4;
  2262. }
  2263. else
  2264. {
  2265. Index++;
  2266. }
  2267. }
  2268. else
  2269. {
  2270. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  2271. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  2272. {
  2273. Result.Insert(F, Index);
  2274. }
  2275. while ((Index <= Result.Length()) && (F == Result[Index]))
  2276. {
  2277. Index++;
  2278. }
  2279. }
  2280. }
  2281. return Result;
  2282. }
  2283. //---------------------------------------------------------------------------
  2284. UnicodeString __fastcall FormatTimeZone(long Sec)
  2285. {
  2286. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  2287. UnicodeString Str;
  2288. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  2289. {
  2290. Str = FORMAT(L"%d", (-Span.Hours));
  2291. }
  2292. else if (Span.Seconds == 0)
  2293. {
  2294. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  2295. }
  2296. else
  2297. {
  2298. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  2299. }
  2300. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  2301. return Str;
  2302. }
  2303. //---------------------------------------------------------------------------
  2304. UnicodeString __fastcall GetTimeZoneLogString()
  2305. {
  2306. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2307. UnicodeString Result =
  2308. FORMAT(L"Current: GMT%s", (FormatTimeZone(CurrentParams->CurrentDifferenceSec)));
  2309. if (!CurrentParams->HasDST())
  2310. {
  2311. Result += FORMAT(L" (%s), No DST", (CurrentParams->StandardName));
  2312. }
  2313. else
  2314. {
  2315. Result +=
  2316. FORMAT(L", Standard: GMT%s (%s), DST: GMT%s (%s), DST Start: %s, DST End: %s",
  2317. (FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->StandardDifferenceSec),
  2318. CurrentParams->StandardName,
  2319. FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->DaylightDifferenceSec),
  2320. CurrentParams->DaylightName,
  2321. CurrentParams->DaylightDate.DateString(),
  2322. CurrentParams->StandardDate.DateString()));
  2323. }
  2324. return Result;
  2325. }
  2326. //---------------------------------------------------------------------------
  2327. bool __fastcall AdjustClockForDSTEnabled()
  2328. {
  2329. // Windows XP deletes the DisableAutoDaylightTimeSet value when it is off
  2330. // (the later versions set it to DynamicDaylightTimeDisabled to 0)
  2331. bool DynamicDaylightTimeDisabled = false;
  2332. TRegistry * Registry = new TRegistry(KEY_READ);
  2333. try
  2334. {
  2335. Registry->RootKey = HKEY_LOCAL_MACHINE;
  2336. if (Registry->OpenKey(L"SYSTEM", false) &&
  2337. Registry->OpenKey(L"CurrentControlSet", false) &&
  2338. Registry->OpenKey(L"Control", false) &&
  2339. Registry->OpenKey(L"TimeZoneInformation", false))
  2340. {
  2341. if (Registry->ValueExists(L"DynamicDaylightTimeDisabled"))
  2342. {
  2343. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DynamicDaylightTimeDisabled");
  2344. }
  2345. // WORKAROUND
  2346. // Windows XP equivalent
  2347. else if (Registry->ValueExists(L"DisableAutoDaylightTimeSet"))
  2348. {
  2349. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DisableAutoDaylightTimeSet");
  2350. }
  2351. }
  2352. delete Registry;
  2353. }
  2354. catch(...)
  2355. {
  2356. }
  2357. return !DynamicDaylightTimeDisabled;
  2358. }
  2359. //---------------------------------------------------------------------------
  2360. UnicodeString __fastcall StandardDatestamp()
  2361. {
  2362. return FormatDateTime(L"yyyy'-'mm'-'dd", ConvertTimestampToUTC(Now()));
  2363. }
  2364. //---------------------------------------------------------------------------
  2365. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  2366. {
  2367. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  2368. }
  2369. //---------------------------------------------------------------------------
  2370. UnicodeString __fastcall StandardTimestamp()
  2371. {
  2372. return StandardTimestamp(Now());
  2373. }
  2374. //---------------------------------------------------------------------------
  2375. static TDateTime TwoSeconds(0, 0, 2, 0);
  2376. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  2377. {
  2378. // "FAT" time precision
  2379. // (when one time is seconds-precision and other is millisecond-precision,
  2380. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  2381. // be treated the same)
  2382. int Result;
  2383. if (T1 == T2)
  2384. {
  2385. // just optimization
  2386. Result = 0;
  2387. }
  2388. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  2389. {
  2390. Result = -1;
  2391. }
  2392. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  2393. {
  2394. Result = 1;
  2395. }
  2396. else
  2397. {
  2398. Result = 0;
  2399. }
  2400. return Result;
  2401. }
  2402. //---------------------------------------------------------------------------
  2403. int __fastcall TimeToMSec(TDateTime T)
  2404. {
  2405. return int(Round(double(T) * double(MSecsPerDay)));
  2406. }
  2407. //---------------------------------------------------------------------------
  2408. int __fastcall TimeToSeconds(TDateTime T)
  2409. {
  2410. return TimeToMSec(T) / MSecsPerSec;
  2411. }
  2412. //---------------------------------------------------------------------------
  2413. int __fastcall TimeToMinutes(TDateTime T)
  2414. {
  2415. return TimeToSeconds(T) / SecsPerMin;
  2416. }
  2417. //---------------------------------------------------------------------------
  2418. static bool __fastcall DoRecursiveDeleteFile(
  2419. const UnicodeString FileName, bool ToRecycleBin, UnicodeString & ErrorPath, int & Deleted)
  2420. {
  2421. bool Result;
  2422. Deleted = 0;
  2423. UnicodeString AErrorPath = FileName;
  2424. if (!ToRecycleBin)
  2425. {
  2426. TSearchRecChecked InitialSearchRec;
  2427. Result = FileSearchRec(FileName, InitialSearchRec);
  2428. if (Result)
  2429. {
  2430. if (!InitialSearchRec.IsDirectory())
  2431. {
  2432. Result = DeleteFile(ApiPath(FileName));
  2433. if (Result)
  2434. {
  2435. Deleted++;
  2436. }
  2437. }
  2438. else
  2439. {
  2440. TSearchRecOwned SearchRec;
  2441. Result = (FindFirstUnchecked(FileName + L"\\*", faAnyFile, SearchRec) == 0);
  2442. if (Result)
  2443. {
  2444. do
  2445. {
  2446. UnicodeString FileName2 = SearchRec.GetFilePath();
  2447. if (SearchRec.IsDirectory())
  2448. {
  2449. if (SearchRec.IsRealFile())
  2450. {
  2451. Result = DoRecursiveDeleteFile(FileName2, DebugAlwaysFalse(ToRecycleBin), AErrorPath, Deleted);
  2452. }
  2453. }
  2454. else
  2455. {
  2456. Result = DeleteFile(ApiPath(FileName2));
  2457. if (!Result)
  2458. {
  2459. AErrorPath = FileName2;
  2460. }
  2461. else
  2462. {
  2463. Deleted++;
  2464. }
  2465. }
  2466. }
  2467. while (Result && (FindNextUnchecked(SearchRec) == 0));
  2468. if (Result)
  2469. {
  2470. Result = RemoveDir(ApiPath(FileName));
  2471. if (Result)
  2472. {
  2473. Deleted++;
  2474. }
  2475. }
  2476. }
  2477. }
  2478. }
  2479. }
  2480. else
  2481. {
  2482. SHFILEOPSTRUCT Data;
  2483. memset(&Data, 0, sizeof(Data));
  2484. Data.hwnd = NULL;
  2485. Data.wFunc = FO_DELETE;
  2486. // SHFileOperation does not support long paths anyway
  2487. UnicodeString FileList(ApiPath(FileName));
  2488. FileList.SetLength(FileList.Length() + 2);
  2489. FileList[FileList.Length() - 1] = L'\0';
  2490. FileList[FileList.Length()] = L'\0';
  2491. Data.pFrom = FileList.c_str();
  2492. Data.pTo = L"\0\0"; // this will actually give one null more than needed
  2493. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  2494. FOF_NOERRORUI | FOF_SILENT;
  2495. if (DebugAlwaysTrue(ToRecycleBin))
  2496. {
  2497. Data.fFlags |= FOF_ALLOWUNDO;
  2498. }
  2499. int ErrorCode = SHFileOperation(&Data);
  2500. Result = (ErrorCode == 0);
  2501. if (!Result)
  2502. {
  2503. // according to MSDN, SHFileOperation may return following non-Win32
  2504. // error codes
  2505. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  2506. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  2507. (ErrorCode == 0x10074))
  2508. {
  2509. ErrorCode = 0;
  2510. }
  2511. SetLastError(ErrorCode);
  2512. }
  2513. if (Result)
  2514. {
  2515. Deleted = 1;
  2516. }
  2517. }
  2518. if (!Result)
  2519. {
  2520. ErrorPath = AErrorPath;
  2521. }
  2522. return Result;
  2523. }
  2524. //---------------------------------------------------------------------------
  2525. bool __fastcall RecursiveDeleteFile(const UnicodeString & FileName, bool ToRecycleBin)
  2526. {
  2527. UnicodeString ErrorPath; // unused
  2528. int Deleted;
  2529. bool Result = DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath, Deleted);
  2530. return Result;
  2531. }
  2532. //---------------------------------------------------------------------------
  2533. int __fastcall RecursiveDeleteFileChecked(const UnicodeString & FileName, bool ToRecycleBin)
  2534. {
  2535. UnicodeString ErrorPath;
  2536. int Deleted;
  2537. if (!DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath, Deleted))
  2538. {
  2539. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (ErrorPath)));
  2540. }
  2541. return Deleted;
  2542. }
  2543. //---------------------------------------------------------------------------
  2544. void __fastcall DeleteFileChecked(const UnicodeString & FileName)
  2545. {
  2546. if (!DeleteFile(ApiPath(FileName)))
  2547. {
  2548. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  2549. }
  2550. }
  2551. //---------------------------------------------------------------------------
  2552. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  2553. {
  2554. unsigned int Result;
  2555. if ((Answers & qaCancel) != 0)
  2556. {
  2557. Result = qaCancel;
  2558. }
  2559. else if ((Answers & qaNo) != 0)
  2560. {
  2561. Result = qaNo;
  2562. }
  2563. else if ((Answers & qaAbort) != 0)
  2564. {
  2565. Result = qaAbort;
  2566. }
  2567. else if ((Answers & qaOK) != 0)
  2568. {
  2569. Result = qaOK;
  2570. }
  2571. else
  2572. {
  2573. DebugFail();
  2574. Result = qaCancel;
  2575. }
  2576. return Result;
  2577. }
  2578. //---------------------------------------------------------------------------
  2579. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  2580. {
  2581. unsigned int Result;
  2582. if (FLAGSET(Answers, qaAbort))
  2583. {
  2584. Result = qaAbort;
  2585. }
  2586. else
  2587. {
  2588. Result = CancelAnswer(Answers);
  2589. }
  2590. return Result;
  2591. }
  2592. //---------------------------------------------------------------------------
  2593. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  2594. {
  2595. unsigned int Result;
  2596. if (FLAGSET(Answers, qaSkip))
  2597. {
  2598. Result = qaSkip;
  2599. }
  2600. else if (FLAGSET(Answers, qaIgnore))
  2601. {
  2602. Result = qaIgnore;
  2603. }
  2604. else if (FLAGSET(Answers, qaYes))
  2605. {
  2606. Result = qaYes;
  2607. }
  2608. else if (FLAGSET(Answers, qaOK))
  2609. {
  2610. Result = qaOK;
  2611. }
  2612. else if (FLAGSET(Answers, qaRetry))
  2613. {
  2614. Result = qaRetry;
  2615. }
  2616. else
  2617. {
  2618. Result = CancelAnswer(Answers);
  2619. }
  2620. return Result;
  2621. }
  2622. //---------------------------------------------------------------------------
  2623. TLibModule * __fastcall FindModule(void * Instance)
  2624. {
  2625. TLibModule * CurModule;
  2626. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  2627. while (CurModule)
  2628. {
  2629. if (CurModule->Instance == (unsigned)Instance)
  2630. {
  2631. break;
  2632. }
  2633. else
  2634. {
  2635. CurModule = CurModule->Next;
  2636. }
  2637. }
  2638. return CurModule;
  2639. }
  2640. //---------------------------------------------------------------------------
  2641. static UnicodeString __fastcall DoLoadStrFrom(HINSTANCE Module, int Ident, unsigned int MaxLength)
  2642. {
  2643. UnicodeString Result;
  2644. Result.SetLength(MaxLength);
  2645. int Length = LoadString(Module, Ident, Result.c_str(), MaxLength);
  2646. Result.SetLength(Length);
  2647. return Result;
  2648. }
  2649. //---------------------------------------------------------------------------
  2650. UnicodeString __fastcall LoadStrFrom(HINSTANCE Module, int Ident)
  2651. {
  2652. // 1024 = what VCL LoadStr limits the string to
  2653. return DoLoadStrFrom(Module, Ident, 1024);
  2654. }
  2655. //---------------------------------------------------------------------------
  2656. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  2657. {
  2658. TLibModule * MainModule = FindModule(HInstance);
  2659. DebugAssert(MainModule != NULL);
  2660. return DoLoadStrFrom((HINSTANCE)MainModule->ResInstance, Ident, MaxLength);
  2661. }
  2662. //---------------------------------------------------------------------------
  2663. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  2664. {
  2665. UnicodeString Result;
  2666. UnicodeString Str = LoadStr(Ident);
  2667. while (Part > 0)
  2668. {
  2669. Result = CutToChar(Str, L'|', false);
  2670. Part--;
  2671. }
  2672. return Result;
  2673. }
  2674. //---------------------------------------------------------------------------
  2675. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  2676. {
  2677. int i = 1;
  2678. while (i <= S.Length())
  2679. {
  2680. switch (S[i])
  2681. {
  2682. case L'+':
  2683. S[i] = ' ';
  2684. break;
  2685. case L'%':
  2686. {
  2687. UnicodeString Hex;
  2688. while ((i + 2 <= S.Length()) && (S[i] == L'%') &&
  2689. IsHex(S[i + 1]) && IsHex(S[i + 2]))
  2690. {
  2691. Hex += S.SubString(i + 1, 2);
  2692. S.Delete(i, 3);
  2693. }
  2694. if (!Hex.IsEmpty())
  2695. {
  2696. RawByteString Bytes = HexToBytes(Hex);
  2697. UnicodeString Chars(UTF8ToString(Bytes));
  2698. S.Insert(Chars, i);
  2699. i += Chars.Length() - 1;
  2700. }
  2701. }
  2702. break;
  2703. }
  2704. i++;
  2705. }
  2706. return S;
  2707. }
  2708. //---------------------------------------------------------------------------
  2709. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, const UnicodeString & DoNotEncode)
  2710. {
  2711. int Index = 1;
  2712. while (Index <= S.Length())
  2713. {
  2714. wchar_t C = S[Index];
  2715. if (IsLetter(C) ||
  2716. IsDigit(C) ||
  2717. (C == L'_') || (C == L'-') || (C == L'.') || (C == L'*') ||
  2718. (DoNotEncode.Pos(C) > 0))
  2719. {
  2720. Index++;
  2721. }
  2722. else
  2723. {
  2724. UTF8String UtfS(S.SubString(Index, 1));
  2725. UnicodeString H;
  2726. for (int Index2 = 1; Index2 <= UtfS.Length(); Index2++)
  2727. {
  2728. H += L"%" + ByteToHex(static_cast<unsigned char>(UtfS[Index2]));
  2729. }
  2730. S.Delete(Index, 1);
  2731. S.Insert(H, Index);
  2732. Index += H.Length();
  2733. }
  2734. }
  2735. return S;
  2736. }
  2737. //---------------------------------------------------------------------------
  2738. UnicodeString __fastcall EncodeUrlString(UnicodeString S)
  2739. {
  2740. return DoEncodeUrl(S, UnicodeString());
  2741. }
  2742. //---------------------------------------------------------------------------
  2743. UnicodeString __fastcall EncodeUrlPath(UnicodeString S)
  2744. {
  2745. return DoEncodeUrl(S, L"/");
  2746. }
  2747. //---------------------------------------------------------------------------
  2748. UnicodeString __fastcall AppendUrlParams(UnicodeString AURL, UnicodeString Params)
  2749. {
  2750. // see also TWebHelpSystem::ShowHelp
  2751. const wchar_t FragmentSeparator = L'#';
  2752. UnicodeString URL = CutToChar(AURL, FragmentSeparator, false);
  2753. if (URL.Pos(L"?") == 0)
  2754. {
  2755. URL += L"?";
  2756. }
  2757. else
  2758. {
  2759. URL += L"&";
  2760. }
  2761. URL += Params;
  2762. AddToList(URL, AURL, FragmentSeparator);
  2763. return URL;
  2764. }
  2765. //---------------------------------------------------------------------------
  2766. UnicodeString __fastcall ExtractFileNameFromUrl(const UnicodeString & Url)
  2767. {
  2768. UnicodeString Result = Url;
  2769. int P = Result.Pos(L"?");
  2770. if (P > 0)
  2771. {
  2772. Result.SetLength(P - 1);
  2773. }
  2774. P = Result.LastDelimiter("/");
  2775. if (DebugAlwaysTrue(P > 0))
  2776. {
  2777. Result.Delete(1, P);
  2778. }
  2779. return Result;
  2780. }
  2781. //---------------------------------------------------------------------------
  2782. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  2783. {
  2784. return ReplaceStr(Caption, L"&", L"&&");
  2785. }
  2786. //---------------------------------------------------------------------------
  2787. // duplicated in console's Main.cpp
  2788. static bool __fastcall DoCutToken(UnicodeString & Str, UnicodeString & Token,
  2789. UnicodeString * RawToken, UnicodeString * Separator, bool EscapeQuotesInQuotesOnly)
  2790. {
  2791. bool Result;
  2792. Token = L"";
  2793. // inspired by Putty's sftp_getcmd() from PSFTP.C
  2794. int Index = 1;
  2795. while ((Index <= Str.Length()) &&
  2796. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2797. {
  2798. Index++;
  2799. }
  2800. if (Index <= Str.Length())
  2801. {
  2802. bool Quoting = false;
  2803. while (Index <= Str.Length())
  2804. {
  2805. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2806. {
  2807. break;
  2808. }
  2809. // With EscapeQuotesInQuotesOnly we escape quotes only within quotes
  2810. // otherwise the "" means " (quote), but it should mean empty string.
  2811. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  2812. (Str[Index + 1] == L'"') && (!EscapeQuotesInQuotesOnly || Quoting))
  2813. {
  2814. Index += 2;
  2815. Token += L'"';
  2816. }
  2817. else if (Str[Index] == L'"')
  2818. {
  2819. Index++;
  2820. Quoting = !Quoting;
  2821. }
  2822. else
  2823. {
  2824. Token += Str[Index];
  2825. Index++;
  2826. }
  2827. }
  2828. if (RawToken != NULL)
  2829. {
  2830. (*RawToken) = Str.SubString(1, Index - 1);
  2831. }
  2832. if (Index <= Str.Length())
  2833. {
  2834. if (Separator != NULL)
  2835. {
  2836. *Separator = Str.SubString(Index, 1);
  2837. }
  2838. Index++;
  2839. }
  2840. else
  2841. {
  2842. if (Separator != NULL)
  2843. {
  2844. *Separator = UnicodeString();
  2845. }
  2846. }
  2847. Str = Str.SubString(Index, Str.Length());
  2848. Result = true;
  2849. }
  2850. else
  2851. {
  2852. Result = false;
  2853. Str = L"";
  2854. }
  2855. return Result;
  2856. }
  2857. //---------------------------------------------------------------------------
  2858. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  2859. UnicodeString * RawToken, UnicodeString * Separator)
  2860. {
  2861. return DoCutToken(Str, Token, RawToken, Separator, false);
  2862. }
  2863. //---------------------------------------------------------------------------
  2864. bool __fastcall CutTokenEx(UnicodeString & Str, UnicodeString & Token,
  2865. UnicodeString * RawToken, UnicodeString * Separator)
  2866. {
  2867. return DoCutToken(Str, Token, RawToken, Separator, true);
  2868. }
  2869. //---------------------------------------------------------------------------
  2870. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  2871. {
  2872. if (!Value.IsEmpty())
  2873. {
  2874. if (!List.IsEmpty() &&
  2875. ((List.Length() < Delimiter.Length()) ||
  2876. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  2877. {
  2878. List += Delimiter;
  2879. }
  2880. List += Value;
  2881. }
  2882. }
  2883. //---------------------------------------------------------------------------
  2884. void AddToShellFileListCommandLine(UnicodeString & List, const UnicodeString & Value)
  2885. {
  2886. UnicodeString Arg = ShellQuoteStr(Value);
  2887. AddToList(List, Arg, L" ");
  2888. }
  2889. //---------------------------------------------------------------------------
  2890. bool __fastcall IsWinVista()
  2891. {
  2892. // Vista is 6.0
  2893. // Win XP is 5.1
  2894. // There also 5.2, what is Windows 2003 or Windows XP 64bit
  2895. // (we consider it WinXP for now)
  2896. return CheckWin32Version(6, 0);
  2897. }
  2898. //---------------------------------------------------------------------------
  2899. bool __fastcall IsWin7()
  2900. {
  2901. return CheckWin32Version(6, 1);
  2902. }
  2903. //---------------------------------------------------------------------------
  2904. bool __fastcall IsWin8()
  2905. {
  2906. return CheckWin32Version(6, 2);
  2907. }
  2908. //---------------------------------------------------------------------------
  2909. bool __fastcall IsWin10()
  2910. {
  2911. return CheckWin32Version(10, 0);
  2912. }
  2913. //---------------------------------------------------------------------------
  2914. static OSVERSIONINFO __fastcall GetWindowsVersion()
  2915. {
  2916. OSVERSIONINFO Result;
  2917. memset(&Result, 0, sizeof(Result));
  2918. Result.dwOSVersionInfoSize = sizeof(Result);
  2919. // Cannot use the VCL Win32MajorVersion+Win32MinorVersion+Win32BuildNumber as
  2920. // on Windows 10 due to some hacking in InitPlatformId, the Win32BuildNumber is lost
  2921. GetVersionEx(&Result);
  2922. return Result;
  2923. }
  2924. //---------------------------------------------------------------------------
  2925. bool __fastcall IsWin10Build(unsigned int BuildNumber)
  2926. {
  2927. // It might be enough to check the dwBuildNumber, as we do in TWinConfiguration::IsDDExtBroken()
  2928. OSVERSIONINFO OSVersionInfo = GetWindowsVersion();
  2929. return
  2930. (OSVersionInfo.dwMajorVersion > 10) ||
  2931. ((OSVersionInfo.dwMajorVersion == 10) && (OSVersionInfo.dwMinorVersion > 0)) ||
  2932. ((OSVersionInfo.dwMajorVersion == 10) && (OSVersionInfo.dwMinorVersion == 0) &&
  2933. (OSVersionInfo.dwBuildNumber >= BuildNumber));
  2934. }
  2935. //---------------------------------------------------------------------------
  2936. bool IsWin11()
  2937. {
  2938. return IsWin10Build(22000);
  2939. }
  2940. //---------------------------------------------------------------------------
  2941. bool __fastcall IsWine()
  2942. {
  2943. HMODULE NtDll = GetModuleHandle(L"ntdll.dll");
  2944. return
  2945. DebugAlwaysTrue(NtDll != NULL) &&
  2946. (GetProcAddress(NtDll, "wine_get_version") != NULL);
  2947. }
  2948. //---------------------------------------------------------------------------
  2949. int GIsUWP = -1;
  2950. UnicodeString GPackageName;
  2951. //---------------------------------------------------------------------------
  2952. static void NeedUWPData()
  2953. {
  2954. if (GIsUWP < 0)
  2955. {
  2956. GIsUWP = 0;
  2957. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  2958. typedef LONG WINAPI (* GetCurrentPackageFamilyNameProc)(UINT32 * packageFamilyNameLength, PWSTR packageFamilyName);
  2959. GetCurrentPackageFamilyNameProc GetCurrentPackageFamilyName =
  2960. (GetCurrentPackageFamilyNameProc)GetProcAddress(Kernel32, "GetCurrentPackageFamilyName");
  2961. UINT32 NameLen = 0;
  2962. if ((GetCurrentPackageFamilyName != NULL) &&
  2963. (GetCurrentPackageFamilyName(&NameLen, NULL) == ERROR_INSUFFICIENT_BUFFER))
  2964. {
  2965. GIsUWP = 1;
  2966. AppLog(L"Is UWP application");
  2967. GPackageName.SetLength(NameLen);
  2968. if (GetCurrentPackageFamilyName(&NameLen, GPackageName.c_str()) == ERROR_SUCCESS)
  2969. {
  2970. PackStr(GPackageName);
  2971. }
  2972. else
  2973. {
  2974. GPackageName = L"err";
  2975. }
  2976. AppLogFmt(L"Package name: %s", (GPackageName));
  2977. }
  2978. else
  2979. {
  2980. AppLog(L"Is not UWP application");
  2981. }
  2982. }
  2983. }
  2984. //---------------------------------------------------------------------------
  2985. bool __fastcall IsUWP()
  2986. {
  2987. NeedUWPData();
  2988. return (GIsUWP > 0);
  2989. }
  2990. //---------------------------------------------------------------------------
  2991. UnicodeString GetPackageName()
  2992. {
  2993. NeedUWPData();
  2994. return GPackageName;
  2995. }
  2996. //---------------------------------------------------------------------------
  2997. bool IsOfficialPackage()
  2998. {
  2999. return (GetPackageName() == OfficialPackage);
  3000. }
  3001. //---------------------------------------------------------------------------
  3002. LCID __fastcall GetDefaultLCID()
  3003. {
  3004. return GetUserDefaultLCID();
  3005. }
  3006. //---------------------------------------------------------------------------
  3007. static UnicodeString ADefaultEncodingName;
  3008. UnicodeString __fastcall DefaultEncodingName()
  3009. {
  3010. if (ADefaultEncodingName.IsEmpty())
  3011. {
  3012. CPINFOEX Info;
  3013. GetCPInfoEx(CP_ACP, 0, &Info);
  3014. ADefaultEncodingName = Info.CodePageName;
  3015. }
  3016. return ADefaultEncodingName;
  3017. }
  3018. //---------------------------------------------------------------------------
  3019. bool _fastcall GetWindowsProductType(DWORD & Type)
  3020. {
  3021. bool Result;
  3022. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  3023. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  3024. TGetProductInfo GetProductInfo =
  3025. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  3026. if (GetProductInfo == NULL)
  3027. {
  3028. Result = false;
  3029. }
  3030. else
  3031. {
  3032. GetProductInfo(Win32MajorVersion, Win32MinorVersion, 0, 0, &Type);
  3033. Result = true;
  3034. }
  3035. return Result;
  3036. }
  3037. //---------------------------------------------------------------------------
  3038. UnicodeString __fastcall WindowsProductName()
  3039. {
  3040. UnicodeString Result;
  3041. TRegistry * Registry = new TRegistry(KEY_READ);
  3042. try
  3043. {
  3044. Registry->RootKey = HKEY_LOCAL_MACHINE;
  3045. if (Registry->OpenKey(L"SOFTWARE", false) &&
  3046. Registry->OpenKey(L"Microsoft", false) &&
  3047. Registry->OpenKey(L"Windows NT", false) &&
  3048. Registry->OpenKey(L"CurrentVersion", false))
  3049. {
  3050. Result = Registry->ReadString(L"ProductName");
  3051. }
  3052. delete Registry;
  3053. }
  3054. catch(...)
  3055. {
  3056. }
  3057. return Result;
  3058. }
  3059. //---------------------------------------------------------------------------
  3060. int __fastcall GetWindowsBuild()
  3061. {
  3062. return GetWindowsVersion().dwBuildNumber;
  3063. }
  3064. //---------------------------------------------------------------------------
  3065. UnicodeString __fastcall WindowsVersion()
  3066. {
  3067. OSVERSIONINFO OSVersionInfo = GetWindowsVersion();
  3068. UnicodeString Result = FORMAT(L"%d.%d.%d", (int(OSVersionInfo.dwMajorVersion), int(OSVersionInfo.dwMinorVersion), int(OSVersionInfo.dwBuildNumber)));
  3069. return Result;
  3070. }
  3071. //---------------------------------------------------------------------------
  3072. UnicodeString __fastcall WindowsVersionLong()
  3073. {
  3074. UnicodeString Result = WindowsVersion();
  3075. AddToList(Result, Win32CSDVersion, L" ");
  3076. return Result;
  3077. }
  3078. //---------------------------------------------------------------------------
  3079. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  3080. {
  3081. UnicodeString FileName =
  3082. IncludeTrailingPathDelimiter(Path) +
  3083. FORMAT(L"wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  3084. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  3085. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  3086. bool Result = (Handle != INVALID_HANDLE_VALUE);
  3087. if (Result)
  3088. {
  3089. CloseHandle(Handle);
  3090. }
  3091. return Result;
  3092. }
  3093. //---------------------------------------------------------------------------
  3094. UnicodeString __fastcall FormatNumber(__int64 Number)
  3095. {
  3096. return FormatFloat(L"#,##0", Number);
  3097. }
  3098. //---------------------------------------------------------------------------
  3099. // simple alternative to FormatBytes
  3100. UnicodeString __fastcall FormatSize(__int64 Size)
  3101. {
  3102. return FormatNumber(Size);
  3103. }
  3104. //---------------------------------------------------------------------------
  3105. UnicodeString __fastcall FormatDateTimeSpan(const UnicodeString TimeFormat, TDateTime DateTime)
  3106. {
  3107. UnicodeString Result;
  3108. if (int(DateTime) > 0)
  3109. {
  3110. Result = IntToStr(int(DateTime)) + L", ";
  3111. }
  3112. // days are decremented, because when there are too many of them,
  3113. // "integer overflow" error occurs
  3114. Result += FormatDateTime(TimeFormat, DateTime - int(DateTime));
  3115. return Result;
  3116. }
  3117. //---------------------------------------------------------------------------
  3118. UnicodeString FormatRelativeTime(const TDateTime & ANow, const TDateTime & AThen, bool DateOnly)
  3119. {
  3120. UnicodeString Result;
  3121. if (DateOnly)
  3122. {
  3123. if (IsSameDay(AThen, ANow - 1))
  3124. {
  3125. Result = LoadStrPart(TIME_RELATIVE, 3);
  3126. }
  3127. else if (IsSameDay(AThen, ANow))
  3128. {
  3129. Result = LoadStrPart(TIME_RELATIVE, 2);
  3130. }
  3131. }
  3132. if (Result.IsEmpty())
  3133. {
  3134. int Part, Num;
  3135. Num = YearsBetween(ANow, AThen);
  3136. if (Num > 1)
  3137. {
  3138. Part = 18;
  3139. }
  3140. else if (Num == 1)
  3141. {
  3142. Part = 17;
  3143. }
  3144. else
  3145. {
  3146. Num = MonthsBetween(ANow, AThen);
  3147. if (Num > 1)
  3148. {
  3149. Part = 16;
  3150. }
  3151. else if (Num == 1)
  3152. {
  3153. Part = 15;
  3154. }
  3155. else
  3156. {
  3157. Num = DaysBetween(ANow, AThen);
  3158. if (Num > 1)
  3159. {
  3160. Part = 12;
  3161. }
  3162. else if (Num == 1)
  3163. {
  3164. Part = 11;
  3165. }
  3166. else
  3167. {
  3168. Num = static_cast<int>(HoursBetween(ANow, AThen));
  3169. if (Num > 1)
  3170. {
  3171. Part = 10;
  3172. }
  3173. else if (Num == 1)
  3174. {
  3175. Part = 9;
  3176. }
  3177. else
  3178. {
  3179. Num = static_cast<int>(MinutesBetween(ANow, AThen));
  3180. if (Num > 1)
  3181. {
  3182. Part = 8;
  3183. }
  3184. else if (Num == 1)
  3185. {
  3186. Part = 7;
  3187. }
  3188. else
  3189. {
  3190. Num = static_cast<int>(SecondsBetween(ANow, AThen));
  3191. if (Num > 1)
  3192. {
  3193. Part = 6;
  3194. }
  3195. else if (Num == 1)
  3196. {
  3197. Part = 5;
  3198. }
  3199. else if (Num == 0)
  3200. {
  3201. Part = 1;
  3202. }
  3203. else
  3204. {
  3205. DebugFail();
  3206. Part = -1;
  3207. }
  3208. }
  3209. }
  3210. }
  3211. }
  3212. }
  3213. if (DebugAlwaysTrue(Part >= 0))
  3214. {
  3215. Result = FORMAT(LoadStrPart(TIME_RELATIVE, Part), (abs(Num)));
  3216. }
  3217. else
  3218. {
  3219. Result = FormatDateTime(L"ddddd", AThen);
  3220. }
  3221. }
  3222. return Result;
  3223. }
  3224. //---------------------------------------------------------------------------
  3225. UnicodeString __fastcall ExtractFileBaseName(const UnicodeString & Path)
  3226. {
  3227. return ChangeFileExt(ExtractFileName(Path), L"");
  3228. }
  3229. //---------------------------------------------------------------------------
  3230. TStringList * __fastcall TextToStringList(const UnicodeString & Text)
  3231. {
  3232. std::unique_ptr<TStringList> List(new TStringList());
  3233. List->Text = Text;
  3234. return List.release();
  3235. }
  3236. //---------------------------------------------------------------------------
  3237. UnicodeString __fastcall StringsToText(TStrings * Strings)
  3238. {
  3239. UnicodeString Result;
  3240. if (Strings->Count == 1)
  3241. {
  3242. Result = Strings->Strings[0];
  3243. }
  3244. else
  3245. {
  3246. Result = Strings->Text;
  3247. }
  3248. return Result;
  3249. }
  3250. //---------------------------------------------------------------------------
  3251. TStringList * __fastcall CommaTextToStringList(const UnicodeString & CommaText)
  3252. {
  3253. std::unique_ptr<TStringList> List(new TStringList());
  3254. List->CommaText = CommaText;
  3255. return List.release();
  3256. }
  3257. //---------------------------------------------------------------------------
  3258. TStrings * __fastcall CloneStrings(TStrings * Strings)
  3259. {
  3260. std::unique_ptr<TStringList> List(new TStringList());
  3261. List->AddStrings(Strings);
  3262. return List.release();
  3263. }
  3264. //---------------------------------------------------------------------------
  3265. UnicodeString __fastcall TrimVersion(UnicodeString Version)
  3266. {
  3267. while ((Version.Pos(L".") != Version.LastDelimiter(L".")) &&
  3268. (Version.SubString(Version.Length() - 1, 2) == L".0"))
  3269. {
  3270. Version.SetLength(Version.Length() - 2);
  3271. }
  3272. return Version;
  3273. }
  3274. //---------------------------------------------------------------------------
  3275. UnicodeString __fastcall FormatVersion(int MajovVersion, int MinorVersion, int Release)
  3276. {
  3277. return
  3278. TrimVersion(FORMAT(L"%d.%d.%d",
  3279. (MajovVersion, MinorVersion, Release)));
  3280. }
  3281. //---------------------------------------------------------------------------
  3282. TFormatSettings __fastcall GetEngFormatSettings()
  3283. {
  3284. return TFormatSettings::Create((TLocaleID)1033);
  3285. }
  3286. //---------------------------------------------------------------------------
  3287. int __fastcall ParseShortEngMonthName(const UnicodeString & MonthStr)
  3288. {
  3289. TFormatSettings FormatSettings = GetEngFormatSettings();
  3290. return IndexStr(MonthStr, FormatSettings.ShortMonthNames, FormatSettings.ShortMonthNames.Size()) + 1;
  3291. }
  3292. //---------------------------------------------------------------------------
  3293. TStringList * __fastcall CreateSortedStringList(bool CaseSensitive, System::Types::TDuplicates Duplicates)
  3294. {
  3295. TStringList * Result = new TStringList();
  3296. Result->CaseSensitive = CaseSensitive;
  3297. Result->Sorted = true;
  3298. Result->Duplicates = Duplicates;
  3299. return Result;
  3300. }
  3301. //---------------------------------------------------------------------------
  3302. static UnicodeString __fastcall NormalizeIdent(UnicodeString Ident)
  3303. {
  3304. int Index = 1;
  3305. while (Index <= Ident.Length())
  3306. {
  3307. if (Ident[Index] == L'-')
  3308. {
  3309. Ident.Delete(Index, 1);
  3310. }
  3311. else
  3312. {
  3313. Index++;
  3314. }
  3315. }
  3316. return Ident;
  3317. }
  3318. //---------------------------------------------------------------------------
  3319. UnicodeString __fastcall FindIdent(const UnicodeString & Ident, TStrings * Idents)
  3320. {
  3321. UnicodeString NormalizedIdent(NormalizeIdent(Ident));
  3322. for (int Index = 0; Index < Idents->Count; Index++)
  3323. {
  3324. if (SameText(NormalizedIdent, NormalizeIdent(Idents->Strings[Index])))
  3325. {
  3326. return Idents->Strings[Index];
  3327. }
  3328. }
  3329. return Ident;
  3330. }
  3331. //---------------------------------------------------------------------------
  3332. static UnicodeString __fastcall GetTlsErrorStr(int Err)
  3333. {
  3334. char * Buffer = new char[512];
  3335. ERR_error_string(Err, Buffer);
  3336. // not sure about the UTF8
  3337. return UnicodeString(UTF8String(Buffer));
  3338. }
  3339. //---------------------------------------------------------------------------
  3340. static FILE * __fastcall OpenCertificate(const UnicodeString & Path)
  3341. {
  3342. FILE * Result = _wfopen(ApiPath(Path).c_str(), L"rb");
  3343. if (Result == NULL)
  3344. {
  3345. int Error = errno;
  3346. throw EOSExtException(MainInstructions(FMTLOAD(CERTIFICATE_OPEN_ERROR, (Path))), Error);
  3347. }
  3348. return Result;
  3349. }
  3350. //---------------------------------------------------------------------------
  3351. struct TPemPasswordCallbackData
  3352. {
  3353. UnicodeString * Passphrase;
  3354. };
  3355. //---------------------------------------------------------------------------
  3356. static int PemPasswordCallback(char * Buf, int Size, int /*RWFlag*/, void * UserData)
  3357. {
  3358. TPemPasswordCallbackData & Data = *reinterpret_cast<TPemPasswordCallbackData *>(UserData);
  3359. UTF8String UtfPassphrase = UTF8String(*Data.Passphrase);
  3360. strncpy(Buf, UtfPassphrase.c_str(), Size);
  3361. Shred(UtfPassphrase);
  3362. Buf[Size - 1] = '\0';
  3363. return strlen(Buf);
  3364. }
  3365. //---------------------------------------------------------------------------
  3366. static bool __fastcall IsTlsPassphraseError(int Error, bool HasPassphrase)
  3367. {
  3368. int ErrorLib = ERR_GET_LIB(Error);
  3369. int ErrorReason = ERR_GET_REASON(Error);
  3370. bool Result =
  3371. ((ErrorLib == ERR_LIB_PKCS12) &&
  3372. (ErrorReason == PKCS12_R_MAC_VERIFY_FAILURE)) ||
  3373. ((ErrorLib == ERR_LIB_PEM) &&
  3374. (ErrorReason == PEM_R_BAD_PASSWORD_READ)) ||
  3375. (HasPassphrase && (ERR_LIB_EVP == ERR_LIB_EVP) &&
  3376. ((ErrorReason == PEM_R_BAD_DECRYPT) || (ErrorReason == PEM_R_BAD_BASE64_DECODE)));
  3377. return Result;
  3378. }
  3379. //---------------------------------------------------------------------------
  3380. static void __fastcall ThrowTlsCertificateErrorIgnorePassphraseErrors(const UnicodeString & Path, bool HasPassphrase)
  3381. {
  3382. int Error = ERR_get_error();
  3383. if (!IsTlsPassphraseError(Error, HasPassphrase))
  3384. {
  3385. throw ExtException(MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (Path))), GetTlsErrorStr(Error));
  3386. }
  3387. }
  3388. //---------------------------------------------------------------------------
  3389. void __fastcall ParseCertificate(const UnicodeString & Path,
  3390. const UnicodeString & Passphrase, X509 *& Certificate, EVP_PKEY *& PrivateKey,
  3391. bool & WrongPassphrase)
  3392. {
  3393. Certificate = NULL;
  3394. PrivateKey = NULL;
  3395. WrongPassphrase = false;
  3396. bool HasPassphrase = !Passphrase.IsEmpty();
  3397. FILE * File;
  3398. // Inspired by neon's ne_ssl_clicert_read
  3399. File = OpenCertificate(Path);
  3400. // openssl pkcs12 -inkey cert.pem -in cert.crt -export -out cert.pfx
  3401. // Binary file
  3402. PKCS12 * Pkcs12 = d2i_PKCS12_fp(File, NULL);
  3403. fclose(File);
  3404. if (Pkcs12 != NULL)
  3405. {
  3406. UTF8String PassphraseUtf(Passphrase);
  3407. bool Result =
  3408. (PKCS12_parse(Pkcs12, PassphraseUtf.c_str(), &PrivateKey, &Certificate, NULL) == 1);
  3409. PKCS12_free(Pkcs12);
  3410. if (!Result)
  3411. {
  3412. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  3413. WrongPassphrase = true;
  3414. }
  3415. }
  3416. else
  3417. {
  3418. ERR_clear_error();
  3419. TPemPasswordCallbackData CallbackUserData;
  3420. // PemPasswordCallback never writes to the .Passphrase
  3421. CallbackUserData.Passphrase = const_cast<UnicodeString *>(&Passphrase);
  3422. File = OpenCertificate(Path);
  3423. // Encrypted:
  3424. // openssl req -x509 -newkey rsa:2048 -keyout cert.pem -out cert.crt
  3425. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  3426. // ...
  3427. // -----END ENCRYPTED PRIVATE KEY-----
  3428. // Not encrypted (add -nodes):
  3429. // -----BEGIN PRIVATE KEY-----
  3430. // ...
  3431. // -----END PRIVATE KEY-----
  3432. // Or (openssl genrsa -out client.key 1024 # used for certificate signing request)
  3433. // -----BEGIN RSA PRIVATE KEY-----
  3434. // ...
  3435. // -----END RSA PRIVATE KEY-----
  3436. PrivateKey = PEM_read_PrivateKey(File, NULL, PemPasswordCallback, &CallbackUserData);
  3437. fclose(File);
  3438. try
  3439. {
  3440. if (PrivateKey == NULL)
  3441. {
  3442. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  3443. WrongPassphrase = true;
  3444. }
  3445. File = OpenCertificate(Path);
  3446. // The file can contain both private and public key
  3447. // (basically cert.pem and cert.crt appended one to each other)
  3448. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  3449. // ...
  3450. // -----END ENCRYPTED PRIVATE KEY-----
  3451. // -----BEGIN CERTIFICATE-----
  3452. // ...
  3453. // -----END CERTIFICATE-----
  3454. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  3455. fclose(File);
  3456. if (Certificate == NULL)
  3457. {
  3458. int Error = ERR_get_error();
  3459. // unlikely
  3460. if (IsTlsPassphraseError(Error, HasPassphrase))
  3461. {
  3462. WrongPassphrase = true;
  3463. }
  3464. else
  3465. {
  3466. UnicodeString CertificatePath = ChangeFileExt(Path, L".cer");
  3467. if (!FileExists(CertificatePath))
  3468. {
  3469. CertificatePath = ChangeFileExt(Path, L".crt");
  3470. }
  3471. if (!FileExists(CertificatePath))
  3472. {
  3473. throw Exception(MainInstructions(FMTLOAD(CERTIFICATE_PUBLIC_KEY_NOT_FOUND, (Path))));
  3474. }
  3475. else
  3476. {
  3477. File = OpenCertificate(CertificatePath);
  3478. // -----BEGIN CERTIFICATE-----
  3479. // ...
  3480. // -----END CERTIFICATE-----
  3481. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  3482. fclose(File);
  3483. if (Certificate == NULL)
  3484. {
  3485. int Base64Error = ERR_get_error();
  3486. File = OpenCertificate(CertificatePath);
  3487. // Binary DER-encoded certificate
  3488. // (as above, with BEGIN/END removed, and decoded from Base64 to binary)
  3489. // openssl x509 -in cert.crt -out client.der.crt -outform DER
  3490. Certificate = d2i_X509_fp(File, NULL);
  3491. fclose(File);
  3492. if (Certificate == NULL)
  3493. {
  3494. int DERError = ERR_get_error();
  3495. UnicodeString Message = MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (CertificatePath)));
  3496. UnicodeString MoreMessages =
  3497. FORMAT(L"Base64: %s\nDER: %s", (GetTlsErrorStr(Base64Error), GetTlsErrorStr(DERError)));
  3498. throw ExtException(Message, MoreMessages);
  3499. }
  3500. }
  3501. }
  3502. }
  3503. }
  3504. }
  3505. __finally
  3506. {
  3507. // We loaded private key, but failed to load certificate, discard the certificate
  3508. // (either exception was thrown or WrongPassphrase)
  3509. if ((PrivateKey != NULL) && (Certificate == NULL))
  3510. {
  3511. EVP_PKEY_free(PrivateKey);
  3512. PrivateKey = NULL;
  3513. }
  3514. // Certificate was verified, but passphrase was wrong when loading private key,
  3515. // so discard the certificate
  3516. else if ((Certificate != NULL) && (PrivateKey == NULL))
  3517. {
  3518. X509_free(Certificate);
  3519. Certificate = NULL;
  3520. }
  3521. }
  3522. }
  3523. }
  3524. //---------------------------------------------------------------------------
  3525. void __fastcall CheckCertificate(const UnicodeString & Path)
  3526. {
  3527. X509 * Certificate;
  3528. EVP_PKEY * PrivateKey;
  3529. bool WrongPassphrase;
  3530. ParseCertificate(Path, L"", Certificate, PrivateKey, WrongPassphrase);
  3531. if (PrivateKey != NULL)
  3532. {
  3533. EVP_PKEY_free(PrivateKey);
  3534. }
  3535. if (Certificate != NULL)
  3536. {
  3537. X509_free(Certificate);
  3538. }
  3539. }
  3540. //---------------------------------------------------------------------------
  3541. const UnicodeString HttpProtocol(L"http");
  3542. const UnicodeString HttpsProtocol(L"https");
  3543. const UnicodeString ProtocolSeparator(L"://");
  3544. //---------------------------------------------------------------------------
  3545. bool __fastcall IsHttpUrl(const UnicodeString & S)
  3546. {
  3547. return StartsText(HttpProtocol + ProtocolSeparator, S);
  3548. }
  3549. //---------------------------------------------------------------------------
  3550. bool __fastcall IsHttpOrHttpsUrl(const UnicodeString & S)
  3551. {
  3552. return
  3553. IsHttpUrl(S) ||
  3554. StartsText(HttpsProtocol + ProtocolSeparator, S);
  3555. }
  3556. //---------------------------------------------------------------------------
  3557. UnicodeString __fastcall ChangeUrlProtocol(const UnicodeString & S, const UnicodeString & Protocol)
  3558. {
  3559. int P = S.Pos(ProtocolSeparator);
  3560. DebugAssert(P > 0);
  3561. return Protocol + ProtocolSeparator + RightStr(S, S.Length() - P - ProtocolSeparator.Length() + 1);
  3562. }
  3563. //---------------------------------------------------------------------------
  3564. const UnicodeString RtfPara(TraceInitStr(L"\\par\n"));
  3565. const UnicodeString AssemblyNamespace(TraceInitStr(L"WinSCP"));
  3566. const UnicodeString TransferOptionsClassName(TraceInitStr(L"TransferOptions"));
  3567. const UnicodeString SessionClassName(TraceInitStr(L"Session"));
  3568. const UnicodeString RtfHyperlinkField(TraceInitStr(L"HYPERLINK"));
  3569. const UnicodeString RtfHyperlinkFieldPrefix(TraceInitStr(RtfHyperlinkField + L" \""));
  3570. const UnicodeString RtfHyperlinkFieldSuffix(TraceInitStr(L"\" "));
  3571. //---------------------------------------------------------------------
  3572. UnicodeString __fastcall RtfColor(int Index)
  3573. {
  3574. return FORMAT(L"\\cf%d", (Index));
  3575. }
  3576. //---------------------------------------------------------------------
  3577. UnicodeString __fastcall RtfText(const UnicodeString & Text, bool Rtf)
  3578. {
  3579. UnicodeString Result = Text;
  3580. if (Rtf)
  3581. {
  3582. int Index = 1;
  3583. while (Index <= Result.Length())
  3584. {
  3585. UnicodeString Replacement;
  3586. wchar_t Ch = Result[Index];
  3587. if ((Ch == L'\\') || (Ch == L'{') || (Ch == L'}'))
  3588. {
  3589. Replacement = FORMAT(L"\\%s", (Ch));
  3590. }
  3591. else if (Ch >= 0x0080)
  3592. {
  3593. Replacement = FORMAT(L"\\u%d?", (int(Ch)));
  3594. }
  3595. if (!Replacement.IsEmpty())
  3596. {
  3597. Result.Delete(Index, 1);
  3598. Result.Insert(Replacement, Index);
  3599. Index += Replacement.Length();
  3600. }
  3601. else
  3602. {
  3603. Index++;
  3604. }
  3605. }
  3606. }
  3607. return Result;
  3608. }
  3609. //---------------------------------------------------------------------
  3610. UnicodeString __fastcall RtfColorText(int Color, const UnicodeString & Text)
  3611. {
  3612. return RtfColor(Color) + L" " + RtfText(Text) + RtfColor(0) + L" ";
  3613. }
  3614. //---------------------------------------------------------------------
  3615. UnicodeString __fastcall RtfColorItalicText(int Color, const UnicodeString & Text)
  3616. {
  3617. return RtfColor(Color) + L"\\i " + RtfText(Text) + L"\\i0" + RtfColor(0) + L" ";
  3618. }
  3619. //---------------------------------------------------------------------
  3620. UnicodeString __fastcall RtfOverrideColorText(const UnicodeString & Text)
  3621. {
  3622. return RtfColorText(1, Text);
  3623. }
  3624. //---------------------------------------------------------------------
  3625. UnicodeString __fastcall RtfKeyword(const UnicodeString & Text)
  3626. {
  3627. return RtfColorText(5, Text);
  3628. }
  3629. //---------------------------------------------------------------------
  3630. UnicodeString __fastcall RtfParameter(const UnicodeString & Text)
  3631. {
  3632. return RtfColorText(6, Text);
  3633. }
  3634. //---------------------------------------------------------------------
  3635. UnicodeString __fastcall RtfString(const UnicodeString & Text)
  3636. {
  3637. return RtfColorText(4, Text);
  3638. }
  3639. //---------------------------------------------------------------------
  3640. UnicodeString __fastcall RtfLink(const UnicodeString & Link, const UnicodeString & RtfText)
  3641. {
  3642. return
  3643. L"{\\field{\\*\\fldinst{" + RtfHyperlinkFieldPrefix + Link + RtfHyperlinkFieldSuffix + L"}}{\\fldrslt{" +
  3644. RtfText + L"}}}";
  3645. }
  3646. //---------------------------------------------------------------------
  3647. UnicodeString __fastcall ScriptCommandLink(const UnicodeString & Command)
  3648. {
  3649. return L"scriptcommand_" + Command;
  3650. }
  3651. //---------------------------------------------------------------------
  3652. UnicodeString __fastcall RtfSwitch(
  3653. const UnicodeString & Switch, const UnicodeString & Link, bool Rtf)
  3654. {
  3655. UnicodeString Result = FORMAT(L"-%s", (Switch));
  3656. if (Rtf)
  3657. {
  3658. Result = RtfLink(Link + L"#" + Switch.LowerCase(), RtfParameter(Result));
  3659. }
  3660. return L" " + Result;
  3661. }
  3662. //---------------------------------------------------------------------
  3663. UnicodeString __fastcall RtfSwitchValue(
  3664. const UnicodeString & Name, const UnicodeString & Link, const UnicodeString & Value, bool Rtf)
  3665. {
  3666. return RtfSwitch(Name, Link, Rtf) + L"=" + Value;
  3667. }
  3668. //---------------------------------------------------------------------
  3669. UnicodeString __fastcall RtfSwitch(
  3670. const UnicodeString & Name, const UnicodeString & Link, const UnicodeString & Value, bool Rtf)
  3671. {
  3672. return RtfSwitchValue(Name, Link, RtfText(FORMAT("\"%s\"", (EscapeParam(Value))), Rtf), Rtf);
  3673. }
  3674. //---------------------------------------------------------------------
  3675. UnicodeString __fastcall RtfSwitch(
  3676. const UnicodeString & Name, const UnicodeString & Link, int Value, bool Rtf)
  3677. {
  3678. return RtfSwitchValue(Name, Link, RtfText(IntToStr(Value), Rtf), Rtf);
  3679. }
  3680. //---------------------------------------------------------------------
  3681. UnicodeString __fastcall RtfRemoveHyperlinks(UnicodeString Text)
  3682. {
  3683. // Remove all tags HYPERLINK "https://www.example.com".
  3684. // See also RtfEscapeParam
  3685. int Index = 1;
  3686. int P;
  3687. while ((P = PosEx(RtfHyperlinkFieldPrefix, Text, Index)) > 0)
  3688. {
  3689. int Index2 = P + RtfHyperlinkFieldPrefix.Length();
  3690. int P2 = PosEx(RtfHyperlinkFieldSuffix, Text, Index2);
  3691. if (P2 > 0)
  3692. {
  3693. Text.Delete(P, P2 - P + RtfHyperlinkFieldSuffix.Length());
  3694. }
  3695. else
  3696. {
  3697. Index = Index2;
  3698. }
  3699. }
  3700. return Text;
  3701. }
  3702. //---------------------------------------------------------------------
  3703. UnicodeString __fastcall RtfEscapeParam(UnicodeString Param, bool PowerShellEscape)
  3704. {
  3705. const UnicodeString Quote(L"\"");
  3706. UnicodeString Escape(Quote);
  3707. if (PowerShellEscape)
  3708. {
  3709. Escape = "`" + Escape + "`";
  3710. }
  3711. // Equivalent of EscapeParam, except that it does not double quotes in HYPERLINK.
  3712. // See also RtfRemoveHyperlinks.
  3713. int Index = 1;
  3714. while (true)
  3715. {
  3716. int P1 = PosEx(Quote, Param, Index);
  3717. if (P1 == 0)
  3718. {
  3719. // no more quotes
  3720. break;
  3721. }
  3722. else
  3723. {
  3724. int P2 = PosEx(RtfHyperlinkFieldPrefix, Param, Index);
  3725. int P3;
  3726. if ((P2 > 0) && (P2 < P1) && ((P3 = PosEx(RtfHyperlinkFieldSuffix, Param, P2)) > 0))
  3727. {
  3728. // skip HYPERLINK
  3729. Index = P3 + RtfHyperlinkFieldSuffix.Length();
  3730. }
  3731. else
  3732. {
  3733. Param.Insert(Escape, P1);
  3734. Index = P1 + (Escape.Length() + Quote.Length());
  3735. }
  3736. }
  3737. }
  3738. return Param;
  3739. }
  3740. //---------------------------------------------------------------------
  3741. static UnicodeString __fastcall RtfCodeComment(const UnicodeString & Text)
  3742. {
  3743. return RtfColorItalicText(2, Text);
  3744. }
  3745. //---------------------------------------------------------------------
  3746. UnicodeString __fastcall AssemblyCommentLine(TAssemblyLanguage Language, const UnicodeString & Text)
  3747. {
  3748. UnicodeString Prefix;
  3749. switch (Language)
  3750. {
  3751. case alCSharp:
  3752. Prefix = L"//";
  3753. break;
  3754. case alVBNET:
  3755. Prefix = L"'";
  3756. break;
  3757. case alPowerShell:
  3758. Prefix = L"#";
  3759. break;
  3760. }
  3761. return RtfCodeComment(Prefix + L" " + Text) + RtfPara;
  3762. }
  3763. //---------------------------------------------------------------------
  3764. UnicodeString __fastcall AssemblyString(TAssemblyLanguage Language, UnicodeString S)
  3765. {
  3766. switch (Language)
  3767. {
  3768. case alCSharp:
  3769. if (S.Pos(L"\\") > 0)
  3770. {
  3771. S = FORMAT(L"@\"%s\"", (ReplaceStr(S, L"\"", L"\"\"")));
  3772. }
  3773. else
  3774. {
  3775. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"\\\"")));
  3776. }
  3777. break;
  3778. case alVBNET:
  3779. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"\"\"")));
  3780. break;
  3781. case alPowerShell:
  3782. S = FORMAT(L"\"%s\"", (ReplaceStr(ReplaceStr(ReplaceStr(S, L"`", L"``"), L"$", L"`$"), L"\"", L"`\"")));
  3783. break;
  3784. default:
  3785. DebugFail();
  3786. break;
  3787. }
  3788. return RtfString(S);
  3789. }
  3790. //---------------------------------------------------------------------
  3791. static UnicodeString __fastcall RtfClass(const UnicodeString & Text)
  3792. {
  3793. return RtfColorText(3, Text);
  3794. }
  3795. //---------------------------------------------------------------------
  3796. UnicodeString __fastcall RtfLibraryClass(const UnicodeString & ClassName)
  3797. {
  3798. return RtfLink(L"library_" + ClassName.LowerCase(), RtfClass(ClassName));
  3799. }
  3800. //---------------------------------------------------------------------
  3801. UnicodeString __fastcall RtfLibraryMethod(const UnicodeString & ClassName, const UnicodeString & MethodName, bool InPage)
  3802. {
  3803. return RtfLink(L"library_" + ClassName.LowerCase() + (InPage ? L"#" : L"_") + MethodName.LowerCase(), RtfOverrideColorText(MethodName));
  3804. }
  3805. //---------------------------------------------------------------------
  3806. static UnicodeString __fastcall RtfLibraryProperty(const UnicodeString & ClassName, const UnicodeString & PropertyName)
  3807. {
  3808. return RtfLink(L"library_" + ClassName.LowerCase() + L"#" + PropertyName.LowerCase(), RtfOverrideColorText(PropertyName));
  3809. }
  3810. //---------------------------------------------------------------------
  3811. UnicodeString __fastcall AssemblyVariableName(TAssemblyLanguage Language, const UnicodeString & ClassName)
  3812. {
  3813. UnicodeString Result = ClassName.SubString(1, 1).LowerCase() + ClassName.SubString(2, ClassName.Length() - 1);
  3814. if (Language == alPowerShell)
  3815. {
  3816. Result = L"$" + Result;
  3817. }
  3818. return Result;
  3819. }
  3820. //---------------------------------------------------------------------
  3821. UnicodeString __fastcall AssemblyStatementSeparator(TAssemblyLanguage Language)
  3822. {
  3823. UnicodeString Result;
  3824. switch (Language)
  3825. {
  3826. case alCSharp:
  3827. Result = L";";
  3828. break;
  3829. case alVBNET:
  3830. case alPowerShell:
  3831. // noop
  3832. break;
  3833. }
  3834. return Result;
  3835. }
  3836. //---------------------------------------------------------------------
  3837. UnicodeString __fastcall AssemblyPropertyRaw(
  3838. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name,
  3839. const UnicodeString & Value, bool Inline)
  3840. {
  3841. UnicodeString Result;
  3842. UnicodeString RtfPropertyAndValue = RtfLibraryProperty(ClassName, Name) + L" = " + Value;
  3843. UnicodeString Indetation = (Inline ? L"" : L" ");
  3844. UnicodeString SpaceOrPara = (Inline ? UnicodeString(L" ") : RtfPara);
  3845. switch (Language)
  3846. {
  3847. case alCSharp:
  3848. Result = Indetation + RtfPropertyAndValue + (Inline ? L"" : L",") + SpaceOrPara;
  3849. break;
  3850. case alVBNET:
  3851. Result = Indetation + L"." + RtfPropertyAndValue + SpaceOrPara;
  3852. break;
  3853. case alPowerShell:
  3854. Result = Indetation + RtfPropertyAndValue + SpaceOrPara;
  3855. break;
  3856. }
  3857. return Result;
  3858. }
  3859. //---------------------------------------------------------------------
  3860. UnicodeString __fastcall AssemblyProperty(
  3861. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name,
  3862. const UnicodeString & Type, const UnicodeString & Member, bool Inline)
  3863. {
  3864. UnicodeString PropertyValue;
  3865. switch (Language)
  3866. {
  3867. case alCSharp:
  3868. case alVBNET:
  3869. PropertyValue = RtfClass(Type) + RtfText(L"." + Member);
  3870. break;
  3871. case alPowerShell:
  3872. PropertyValue = RtfText(L"[" + AssemblyNamespace + L".") + RtfClass(Type) + RtfText(L"]::" + Member);
  3873. break;
  3874. }
  3875. return AssemblyPropertyRaw(Language, ClassName, Name, PropertyValue, Inline);
  3876. }
  3877. //---------------------------------------------------------------------
  3878. UnicodeString __fastcall AssemblyProperty(
  3879. TAssemblyLanguage Language, const UnicodeString & ClassName,
  3880. const UnicodeString & Name, const UnicodeString & Value, bool Inline)
  3881. {
  3882. return AssemblyPropertyRaw(Language, ClassName, Name, AssemblyString(Language, Value), Inline);
  3883. }
  3884. //---------------------------------------------------------------------
  3885. UnicodeString __fastcall AssemblyProperty(
  3886. TAssemblyLanguage Language, const UnicodeString & ClassName,
  3887. const UnicodeString & Name, int Value, bool Inline)
  3888. {
  3889. return AssemblyPropertyRaw(Language, ClassName, Name, IntToStr(Value), Inline);
  3890. }
  3891. //---------------------------------------------------------------------
  3892. UnicodeString __fastcall AssemblyBoolean(TAssemblyLanguage Language, bool Value)
  3893. {
  3894. UnicodeString Result;
  3895. switch (Language)
  3896. {
  3897. case alCSharp:
  3898. Result = (Value ? L"true" : L"false");
  3899. break;
  3900. case alVBNET:
  3901. Result = (Value ? L"True" : L"False");
  3902. break;
  3903. case alPowerShell:
  3904. Result = (Value ? L"$True" : L"$False");
  3905. break;
  3906. }
  3907. return Result;
  3908. }
  3909. //---------------------------------------------------------------------
  3910. UnicodeString __fastcall AssemblyProperty(
  3911. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name, bool Value, bool Inline)
  3912. {
  3913. UnicodeString PropertyValue = AssemblyBoolean(Language, Value);
  3914. return AssemblyPropertyRaw(Language, ClassName, Name, PropertyValue, Inline);
  3915. }
  3916. //---------------------------------------------------------------------
  3917. UnicodeString __fastcall AssemblyNewClassInstance(TAssemblyLanguage Language, const UnicodeString & ClassName, bool Inline)
  3918. {
  3919. UnicodeString VariableName = AssemblyVariableName(Language, ClassName);
  3920. UnicodeString RtfClass = RtfLibraryClass(ClassName);
  3921. UnicodeString Result;
  3922. switch (Language)
  3923. {
  3924. case alCSharp:
  3925. if (!Inline)
  3926. {
  3927. Result += RtfClass + RtfText(L" " + VariableName + L" = ");
  3928. }
  3929. Result += RtfKeyword(L"new") + RtfText(L" ") + RtfClass;
  3930. break;
  3931. case alVBNET:
  3932. if (!Inline)
  3933. {
  3934. Result += RtfText(VariableName + L" ") + RtfKeyword(L"As") + RtfText(L" ");
  3935. }
  3936. Result += RtfKeyword(L"New") + RtfText(" ") + RtfClass;
  3937. break;
  3938. case alPowerShell:
  3939. if (!Inline)
  3940. {
  3941. Result += RtfText(VariableName + L" = ");
  3942. }
  3943. Result += RtfKeyword(L"New-Object") + RtfText(L" " + AssemblyNamespace + L".") + RtfClass;
  3944. break;
  3945. }
  3946. return Result;
  3947. }
  3948. //---------------------------------------------------------------------
  3949. UnicodeString __fastcall AssemblyVariableDeclaration(TAssemblyLanguage Language)
  3950. {
  3951. UnicodeString Result;
  3952. switch (Language)
  3953. {
  3954. case alVBNET:
  3955. Result = RtfKeyword(L"Dim") + RtfText(L" ");
  3956. break;
  3957. }
  3958. return Result;
  3959. }
  3960. //---------------------------------------------------------------------
  3961. UnicodeString __fastcall AssemblyNewClassInstanceStart(
  3962. TAssemblyLanguage Language, const UnicodeString & ClassName, bool Inline)
  3963. {
  3964. UnicodeString SpaceOrPara = (Inline ? UnicodeString(L" ") : RtfPara);
  3965. UnicodeString Result;
  3966. if (!Inline)
  3967. {
  3968. Result += AssemblyVariableDeclaration(Language);
  3969. }
  3970. Result += AssemblyNewClassInstance(Language, ClassName, Inline);
  3971. switch (Language)
  3972. {
  3973. case alCSharp:
  3974. Result += SpaceOrPara + RtfText(L"{") + SpaceOrPara;
  3975. break;
  3976. case alVBNET:
  3977. // Historically we use Dim .. With instead of object initilizer.
  3978. // But for inline use, we have to use object initialize.
  3979. // We should consistently always use object initilizers.
  3980. // Unfortunatelly VB.NET object initializer (contrary to C#) does not allow trailing comma.
  3981. Result += SpaceOrPara + RtfKeyword(L"With");
  3982. if (Inline)
  3983. {
  3984. Result += RtfText(L" { ");
  3985. }
  3986. else
  3987. {
  3988. Result += RtfText(L" " + AssemblyVariableName(Language, ClassName)) + RtfPara;
  3989. }
  3990. break;
  3991. case alPowerShell:
  3992. Result += RtfText(" -Property @{") + SpaceOrPara;
  3993. break;
  3994. }
  3995. return Result;
  3996. }
  3997. //---------------------------------------------------------------------
  3998. UnicodeString __fastcall AssemblyNewClassInstanceEnd(TAssemblyLanguage Language, bool Inline)
  3999. {
  4000. UnicodeString InlineEnd = RtfText(L"}");
  4001. UnicodeString Result;
  4002. switch (Language)
  4003. {
  4004. case alCSharp:
  4005. if (Inline)
  4006. {
  4007. Result = InlineEnd;
  4008. }
  4009. else
  4010. {
  4011. Result = RtfText(L"};") + RtfPara;
  4012. }
  4013. break;
  4014. case alVBNET:
  4015. if (Inline)
  4016. {
  4017. Result = InlineEnd;
  4018. }
  4019. else
  4020. {
  4021. Result = RtfKeyword(L"End With") + RtfPara;
  4022. }
  4023. break;
  4024. case alPowerShell:
  4025. if (Inline)
  4026. {
  4027. Result = InlineEnd;
  4028. }
  4029. else
  4030. {
  4031. Result = RtfText(L"}") + RtfPara;
  4032. }
  4033. break;
  4034. }
  4035. return Result;
  4036. }
  4037. //---------------------------------------------------------------------------
  4038. UnicodeString __fastcall AssemblyAddRawSettings(
  4039. TAssemblyLanguage Language, TStrings * RawSettings, const UnicodeString & ClassName,
  4040. const UnicodeString & MethodName)
  4041. {
  4042. UnicodeString Result;
  4043. for (int Index = 0; Index < RawSettings->Count; Index++)
  4044. {
  4045. UnicodeString Name = RawSettings->Names[Index];
  4046. UnicodeString Value = RawSettings->ValueFromIndex[Index];
  4047. UnicodeString AddRawSettingsMethod =
  4048. RtfLibraryMethod(ClassName, MethodName, false) +
  4049. FORMAT(L"(%s, %s)", (AssemblyString(Language, Name), AssemblyString(Language, Value)));
  4050. UnicodeString VariableName = AssemblyVariableName(Language, ClassName);
  4051. Result += RtfText(VariableName + L".") + AddRawSettingsMethod + AssemblyStatementSeparator(Language) + RtfPara;
  4052. }
  4053. return Result;
  4054. }
  4055. //---------------------------------------------------------------------------
  4056. void __fastcall LoadScriptFromFile(UnicodeString FileName, TStrings * Lines, bool FallbackToAnsi)
  4057. {
  4058. std::unique_ptr<TFileStream> Stream(new TFileStream(ApiPath(FileName), fmOpenRead | fmShareDenyWrite));
  4059. // Simple stream reading, to make it work with named pipes too, not only with physical files
  4060. TBytes Buffer;
  4061. Buffer.Length = 10*1024;
  4062. int Read;
  4063. int Offset = 0;
  4064. do
  4065. {
  4066. Read = Stream->Read(Buffer, Offset, Buffer.Length - Offset);
  4067. Offset += Read;
  4068. if (Offset > Buffer.Length / 2)
  4069. {
  4070. Buffer.Length = Buffer.Length * 2;
  4071. }
  4072. }
  4073. while (Read > 0);
  4074. Buffer.Length = Offset;
  4075. TEncoding * Encoding = NULL;
  4076. int PreambleSize = TEncoding::GetBufferEncoding(Buffer, Encoding, TEncoding::UTF8);
  4077. UnicodeString S;
  4078. try
  4079. {
  4080. S = Encoding->GetString(Buffer, PreambleSize, Buffer.Length - PreambleSize);
  4081. }
  4082. catch (EEncodingError & E)
  4083. {
  4084. if (FallbackToAnsi)
  4085. {
  4086. S = TEncoding::ANSI->GetString(Buffer);
  4087. }
  4088. else
  4089. {
  4090. throw ExtException(LoadStr(TEXT_FILE_ENCODING), &E);
  4091. }
  4092. }
  4093. Lines->Text = S;
  4094. }
  4095. //---------------------------------------------------------------------------
  4096. UnicodeString __fastcall StripEllipsis(const UnicodeString & S)
  4097. {
  4098. UnicodeString Result = S;
  4099. if (Result.SubString(Result.Length() - Ellipsis.Length() + 1, Ellipsis.Length()) == Ellipsis)
  4100. {
  4101. Result.SetLength(Result.Length() - Ellipsis.Length());
  4102. Result = Result.TrimRight();
  4103. }
  4104. return Result;
  4105. }
  4106. //---------------------------------------------------------------------------
  4107. UnicodeString __fastcall GetFileMimeType(const UnicodeString & FileName)
  4108. {
  4109. wchar_t * MimeOut = NULL;
  4110. UnicodeString Result;
  4111. if (FindMimeFromData(NULL, FileName.c_str(), NULL, 0, NULL, FMFD_URLASFILENAME, &MimeOut, 0) == S_OK)
  4112. {
  4113. Result = MimeOut;
  4114. CoTaskMemFree(MimeOut);
  4115. }
  4116. return Result;
  4117. }
  4118. //---------------------------------------------------------------------------
  4119. TStrings * TlsCipherList()
  4120. {
  4121. std::unique_ptr<TStrings> Result(new TStringList());
  4122. const SSL_METHOD * Method = DTLS_client_method();
  4123. SSL_CTX * Ctx = SSL_CTX_new(Method);
  4124. SSL * Ssl = SSL_new(Ctx);
  4125. int Index = 0;
  4126. const char * CipherName;
  4127. do
  4128. {
  4129. CipherName = SSL_get_cipher_list(Ssl, Index);
  4130. Index++;
  4131. if (CipherName != NULL)
  4132. {
  4133. Result->Add(UnicodeString(CipherName));
  4134. }
  4135. }
  4136. while (CipherName != NULL);
  4137. return Result.release();
  4138. }
  4139. //---------------------------------------------------------------------------
  4140. void SetStringValueEvenIfEmpty(TStrings * Strings, const UnicodeString & Name, const UnicodeString & Value)
  4141. {
  4142. if (Value.IsEmpty())
  4143. {
  4144. int Index = Strings->IndexOfName(Name);
  4145. if (Index < 0)
  4146. {
  4147. Index = Strings->Add(L"");
  4148. }
  4149. UnicodeString Line = Name + Strings->NameValueSeparator;
  4150. Strings->Strings[Index] = Line;
  4151. }
  4152. else
  4153. {
  4154. Strings->Values[Name] = Value;
  4155. }
  4156. }
  4157. //---------------------------------------------------------------------------
  4158. DWORD __fastcall GetParentProcessId(HANDLE Snapshot, DWORD ProcessId)
  4159. {
  4160. DWORD Result = 0;
  4161. PROCESSENTRY32 ProcessEntry;
  4162. memset(&ProcessEntry, sizeof(ProcessEntry), 0);
  4163. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  4164. if (Process32First(Snapshot, &ProcessEntry))
  4165. {
  4166. do
  4167. {
  4168. if (ProcessEntry.th32ProcessID == ProcessId)
  4169. {
  4170. Result = ProcessEntry.th32ParentProcessID;
  4171. }
  4172. } while (Process32Next(Snapshot, &ProcessEntry));
  4173. }
  4174. return Result;
  4175. }
  4176. //---------------------------------------------------------------------------
  4177. static UnicodeString GetProcessName(DWORD ProcessId)
  4178. {
  4179. UnicodeString Result;
  4180. HANDLE Process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessId);
  4181. // is common, when the parent process is installer, so we ignore it
  4182. if (Process)
  4183. {
  4184. Result.SetLength(MAX_PATH);
  4185. DWORD Len = GetModuleFileNameEx(Process, NULL, Result.c_str(), Result.Length());
  4186. Result.SetLength(Len);
  4187. // is common too, for some reason
  4188. if (!Result.IsEmpty())
  4189. {
  4190. Result = ExtractProgramName(FormatCommand(Result, UnicodeString()));
  4191. }
  4192. CloseHandle(Process);
  4193. }
  4194. return Result;
  4195. }
  4196. //---------------------------------------------------------------------------
  4197. UnicodeString ParentProcessName;
  4198. //---------------------------------------------------------------------------
  4199. UnicodeString __fastcall GetAncestorProcessName(int Levels)
  4200. {
  4201. UnicodeString Result;
  4202. bool Parent = (Levels == 1);
  4203. if (Parent && !ParentProcessName.IsEmpty())
  4204. {
  4205. Result = ParentProcessName;
  4206. }
  4207. else
  4208. {
  4209. try
  4210. {
  4211. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  4212. DWORD ProcessId = GetCurrentProcessId();
  4213. typedef std::vector<DWORD> TProcesses;
  4214. TProcesses Processes;
  4215. // Either more to go (>0) or collecting all levels (-1 from GetAncestorProcessNames)
  4216. while ((Levels != 0) &&
  4217. (Levels > -20) && // prevent infinite loops
  4218. (ProcessId != 0))
  4219. {
  4220. const UnicodeString Sep(L", ");
  4221. ProcessId = GetParentProcessId(Snapshot, ProcessId);
  4222. // When ancestor process is terminated and another process reuses its ID, we may get a cycle.
  4223. TProcesses::const_iterator I = std::find(Processes.begin(), Processes.end(), ProcessId);
  4224. if (I != Processes.end())
  4225. {
  4226. int Index = I - Processes.begin();
  4227. AddToList(Result, FORMAT(L"cycle-%d", (Index)), Sep);
  4228. ProcessId = 0;
  4229. }
  4230. else
  4231. {
  4232. Processes.push_back(ProcessId);
  4233. if ((Levels < 0) && (ProcessId != 0))
  4234. {
  4235. UnicodeString Name = GetProcessName(ProcessId);
  4236. if (Name.IsEmpty())
  4237. {
  4238. Name = L"...";
  4239. ProcessId = 0;
  4240. }
  4241. AddToList(Result, Name, Sep);
  4242. }
  4243. Levels--;
  4244. }
  4245. }
  4246. if (Levels >= 0)
  4247. {
  4248. if (ProcessId == 0)
  4249. {
  4250. Result = L"err-notfound";
  4251. }
  4252. else
  4253. {
  4254. Result = GetProcessName(ProcessId);
  4255. }
  4256. }
  4257. else if (Result.IsEmpty())
  4258. {
  4259. Result = L"n/a";
  4260. }
  4261. CloseHandle(Snapshot);
  4262. }
  4263. catch (...)
  4264. {
  4265. Result = L"err-except";
  4266. }
  4267. if (Parent)
  4268. {
  4269. ParentProcessName = Result;
  4270. }
  4271. }
  4272. return Result;
  4273. }
  4274. //---------------------------------------------------------------------------
  4275. UnicodeString AncestorProcessNames;
  4276. //---------------------------------------------------------------------------
  4277. UnicodeString GetAncestorProcessNames()
  4278. {
  4279. if (AncestorProcessNames.IsEmpty())
  4280. {
  4281. AncestorProcessNames = GetAncestorProcessName(-1);
  4282. }
  4283. return AncestorProcessNames;
  4284. }
  4285. //---------------------------------------------------------------------------
  4286. void NotImplemented()
  4287. {
  4288. DebugFail();
  4289. throw Exception(L"Not implemented");
  4290. }
  4291. //---------------------------------------------------------------------------
  4292. UnicodeString GetDividerLine()
  4293. {
  4294. return UnicodeString::StringOfChar(L'-', 27);
  4295. }