Common.cpp 137 KB

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