Common.cpp 137 KB

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