Common.cpp 138 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664
  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. // BytesToHex would encode with opposite/unexpected endianness
  1356. return ByteToHex(Ch >> 8, UpperCase) + ByteToHex(Ch & 0xFF, UpperCase);
  1357. }
  1358. //---------------------------------------------------------------------------
  1359. RawByteString __fastcall HexToBytes(const UnicodeString Hex)
  1360. {
  1361. static UnicodeString Digits = L"0123456789ABCDEF";
  1362. RawByteString Result;
  1363. int L, P1, P2;
  1364. L = Hex.Length();
  1365. if (L % 2 == 0)
  1366. {
  1367. for (int i = 1; i <= Hex.Length(); i += 2)
  1368. {
  1369. P1 = Digits.Pos(towupper(Hex[i]));
  1370. P2 = Digits.Pos(towupper(Hex[i + 1]));
  1371. if (P1 <= 0 || P2 <= 0)
  1372. {
  1373. Result = L"";
  1374. break;
  1375. }
  1376. else
  1377. {
  1378. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  1379. }
  1380. }
  1381. }
  1382. return Result;
  1383. }
  1384. //---------------------------------------------------------------------------
  1385. unsigned char __fastcall HexToByte(const UnicodeString Hex)
  1386. {
  1387. static UnicodeString Digits = L"0123456789ABCDEF";
  1388. DebugAssert(Hex.Length() == 2);
  1389. int P1 = Digits.Pos(towupper(Hex[1]));
  1390. int P2 = Digits.Pos(towupper(Hex[2]));
  1391. return
  1392. static_cast<unsigned char>(((P1 <= 0) || (P2 <= 0)) ? 0 : (((P1 - 1) << 4) + (P2 - 1)));
  1393. }
  1394. //---------------------------------------------------------------------------
  1395. bool __fastcall IsLowerCaseLetter(wchar_t Ch)
  1396. {
  1397. return (Ch >= 'a') && (Ch <= 'z');
  1398. }
  1399. //---------------------------------------------------------------------------
  1400. bool __fastcall IsUpperCaseLetter(wchar_t Ch)
  1401. {
  1402. return (Ch >= 'A') && (Ch <= 'Z');
  1403. }
  1404. //---------------------------------------------------------------------------
  1405. bool __fastcall IsLetter(wchar_t Ch)
  1406. {
  1407. return IsLowerCaseLetter(Ch) || IsUpperCaseLetter(Ch);
  1408. }
  1409. //---------------------------------------------------------------------------
  1410. bool __fastcall IsDigit(wchar_t Ch)
  1411. {
  1412. return (Ch >= '0') && (Ch <= '9');
  1413. }
  1414. //---------------------------------------------------------------------------
  1415. bool __fastcall IsHex(wchar_t Ch)
  1416. {
  1417. return
  1418. IsDigit(Ch) ||
  1419. ((Ch >= 'A') && (Ch <= 'F')) ||
  1420. ((Ch >= 'a') && (Ch <= 'f'));
  1421. }
  1422. //---------------------------------------------------------------------------
  1423. TSearchRecSmart::TSearchRecSmart()
  1424. {
  1425. FLastWriteTimeSource.dwLowDateTime = 0;
  1426. FLastWriteTimeSource.dwHighDateTime = 0;
  1427. }
  1428. //---------------------------------------------------------------------------
  1429. void TSearchRecSmart::Clear()
  1430. {
  1431. Size = 0;
  1432. Attr = 0;
  1433. Name = TFileName();
  1434. ExcludeAttr = 0;
  1435. FindHandle = 0;
  1436. memset(&FindData, 0, sizeof(FindData));
  1437. FLastWriteTimeSource.dwLowDateTime = 0;
  1438. FLastWriteTimeSource.dwHighDateTime = 0;
  1439. }
  1440. //---------------------------------------------------------------------------
  1441. // This can be replaced with TSearchRec.TimeStamp
  1442. TDateTime TSearchRecSmart::GetLastWriteTime() const
  1443. {
  1444. if ((FindData.ftLastWriteTime.dwLowDateTime != FLastWriteTimeSource.dwLowDateTime) ||
  1445. (FindData.ftLastWriteTime.dwHighDateTime != FLastWriteTimeSource.dwHighDateTime))
  1446. {
  1447. FLastWriteTimeSource = FindData.ftLastWriteTime;
  1448. FLastWriteTime = FileTimeToDateTime(FLastWriteTimeSource);
  1449. }
  1450. return FLastWriteTime;
  1451. }
  1452. //---------------------------------------------------------------------------
  1453. bool TSearchRecSmart::IsRealFile() const
  1454. {
  1455. return ::IsRealFile(Name);
  1456. }
  1457. //---------------------------------------------------------------------------
  1458. bool TSearchRecSmart::IsDirectory() const
  1459. {
  1460. return FLAGSET(Attr, faDirectory);
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. bool TSearchRecSmart::IsHidden() const
  1464. {
  1465. return FLAGSET(Attr, faHidden);
  1466. }
  1467. //---------------------------------------------------------------------------
  1468. UnicodeString TSearchRecChecked::GetFilePath() const
  1469. {
  1470. return CombinePaths(Dir, Name);
  1471. }
  1472. //---------------------------------------------------------------------------
  1473. TSearchRecOwned::~TSearchRecOwned()
  1474. {
  1475. if (Opened)
  1476. {
  1477. FindClose(*this);
  1478. }
  1479. }
  1480. //---------------------------------------------------------------------------
  1481. void TSearchRecOwned::Close()
  1482. {
  1483. FindClose(*this);
  1484. Opened = false;
  1485. }
  1486. //---------------------------------------------------------------------------
  1487. int __fastcall FindCheck(int Result, const UnicodeString & Path)
  1488. {
  1489. if ((Result != ERROR_SUCCESS) &&
  1490. (Result != ERROR_FILE_NOT_FOUND) &&
  1491. (Result != ERROR_NO_MORE_FILES))
  1492. {
  1493. throw EOSExtException(FMTLOAD(FIND_FILE_ERROR, (Path)), Result);
  1494. }
  1495. return Result;
  1496. }
  1497. //---------------------------------------------------------------------------
  1498. int __fastcall FindFirstUnchecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1499. {
  1500. F.Path = Path;
  1501. F.Dir = ExtractFilePath(Path);
  1502. int Result = FindFirst(ApiPath(Path), Attr, F);
  1503. F.Opened = (Result == 0);
  1504. return Result;
  1505. }
  1506. //---------------------------------------------------------------------------
  1507. int __fastcall FindFirstChecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1508. {
  1509. int Result = FindFirstUnchecked(Path, Attr, F);
  1510. return FindCheck(Result, F.Path);
  1511. }
  1512. //---------------------------------------------------------------------------
  1513. // Equivalent to FindNext, just to complement to FindFirstUnchecked
  1514. int __fastcall FindNextUnchecked(TSearchRecChecked & F)
  1515. {
  1516. return FindNext(F);
  1517. }
  1518. //---------------------------------------------------------------------------
  1519. // It can make sense to use FindNextChecked, even if unchecked FindFirst is used.
  1520. // I.e. even if we do not care that FindFirst failed, if FindNext
  1521. // fails after successful FindFirst, it means some terrible problem
  1522. int __fastcall FindNextChecked(TSearchRecChecked & F)
  1523. {
  1524. return FindCheck(FindNextUnchecked(F), F.Path);
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. bool __fastcall FileSearchRec(const UnicodeString FileName, TSearchRec & Rec)
  1528. {
  1529. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1530. bool Result = (FindFirst(ApiPath(FileName), FindAttrs, Rec) == 0);
  1531. if (Result)
  1532. {
  1533. FindClose(Rec);
  1534. }
  1535. return Result;
  1536. }
  1537. //---------------------------------------------------------------------------
  1538. void CopySearchRec(const TSearchRec & Source, TSearchRec & Dest)
  1539. {
  1540. // Strangely issues a compiler warning (W8111 due to TSearchRec::Time), when used in Script.cpp, but not here.
  1541. Dest = Source;
  1542. }
  1543. //---------------------------------------------------------------------------
  1544. bool __fastcall IsRealFile(const UnicodeString & FileName)
  1545. {
  1546. return (FileName != THISDIRECTORY) && (FileName != PARENTDIRECTORY);
  1547. }
  1548. //---------------------------------------------------------------------------
  1549. UnicodeString GetOSInfo()
  1550. {
  1551. UnicodeString Result = WindowsVersionLong();
  1552. AddToList(Result, WindowsProductName(), TitleSeparator);
  1553. return Result;
  1554. }
  1555. //---------------------------------------------------------------------------
  1556. UnicodeString GetEnvironmentInfo()
  1557. {
  1558. UnicodeString Result = FORMAT(L"WinSCP %s (OS %s)", (Configuration->VersionStr, GetOSInfo()));
  1559. return Result;
  1560. }
  1561. //---------------------------------------------------------------------------
  1562. void __fastcall ProcessLocalDirectory(UnicodeString DirName,
  1563. TProcessLocalFileEvent CallBackFunc, void * Param,
  1564. int FindAttrs)
  1565. {
  1566. DebugAssert(CallBackFunc);
  1567. if (FindAttrs < 0)
  1568. {
  1569. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1570. }
  1571. TSearchRecOwned SearchRec;
  1572. if (FindFirstChecked(CombinePaths(DirName, AnyMask), FindAttrs, SearchRec) == 0)
  1573. {
  1574. do
  1575. {
  1576. if (SearchRec.IsRealFile())
  1577. {
  1578. CallBackFunc(SearchRec.GetFilePath(), SearchRec, Param);
  1579. }
  1580. } while (FindNextChecked(SearchRec) == 0);
  1581. }
  1582. }
  1583. //---------------------------------------------------------------------------
  1584. int __fastcall FileGetAttrFix(const UnicodeString & FileName)
  1585. {
  1586. // Already called with ApiPath
  1587. int Result;
  1588. int Tries = 2;
  1589. do
  1590. {
  1591. // WORKAROUND:
  1592. // FileGetAttr when called for link with FollowLink set (default) will always fail on pre-Vista
  1593. // as it calls InternalGetFileNameFromSymLink, which test for CheckWin32Version(6, 0)
  1594. Result = GetFileAttributes(FileName.c_str());
  1595. if ((Result >= 0) && FLAGSET(Result, faSymLink) && IsWinVista())
  1596. {
  1597. try
  1598. {
  1599. UnicodeString TargetName;
  1600. // WORKAROUND:
  1601. // On Samba, InternalGetFileNameFromSymLink fails and returns true but empty target.
  1602. // That confuses FileGetAttr, which returns attributes of the parent folder instead.
  1603. // Using FileGetSymLinkTarget solves the problem, as it returns false.
  1604. if (!FileGetSymLinkTarget(FileName, TargetName))
  1605. {
  1606. // FileGetAttr would return faInvalid (-1), but we want to allow an upload from Samba,
  1607. // so returning the symlink attributes => noop
  1608. }
  1609. else
  1610. {
  1611. Result = GetFileAttributes(ApiPath(TargetName).c_str());
  1612. }
  1613. }
  1614. catch (EOSError & E)
  1615. {
  1616. Result = -1;
  1617. }
  1618. catch (EDirectoryNotFoundException & E) // throws by FileSystemAttributes
  1619. {
  1620. Result = -1;
  1621. }
  1622. }
  1623. Tries--;
  1624. }
  1625. // When referring to files in some special symlinked locations
  1626. // (like a deduplicated drive or a commvault archive), the first call to FileGetAttr failed.
  1627. // Possibly this issue is resolved by our re-implementation of FileGetAttr above.
  1628. // But as we have no way to test it, keeping the retry here.
  1629. while ((Result < 0) && (Tries > 0));
  1630. return Result;
  1631. }
  1632. //---------------------------------------------------------------------------
  1633. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  1634. {
  1635. try
  1636. {
  1637. TDateTime DateTime = EncodeDate(Year, Month, Day);
  1638. return DateTime;
  1639. }
  1640. catch (EConvertError & E)
  1641. {
  1642. throw EConvertError(FORMAT(L"%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  1643. }
  1644. }
  1645. //---------------------------------------------------------------------------
  1646. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  1647. {
  1648. try
  1649. {
  1650. TDateTime DateTime = EncodeTime(Hour, Min, Sec, MSec);
  1651. return DateTime;
  1652. }
  1653. catch (EConvertError & E)
  1654. {
  1655. throw EConvertError(FORMAT(L"%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  1656. }
  1657. }
  1658. //---------------------------------------------------------------------------
  1659. TDateTime __fastcall SystemTimeToDateTimeVerbose(const SYSTEMTIME & SystemTime)
  1660. {
  1661. try
  1662. {
  1663. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1664. return DateTime;
  1665. }
  1666. catch (EConvertError & E)
  1667. {
  1668. 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))));
  1669. }
  1670. }
  1671. //---------------------------------------------------------------------------
  1672. struct TDateTimeParams
  1673. {
  1674. TDateTime UnixEpoch;
  1675. double BaseDifference;
  1676. long BaseDifferenceSec;
  1677. // All Current* are actually global, not per-year and
  1678. // are valid for Year 0 (current) only
  1679. double CurrentDaylightDifference;
  1680. long CurrentDaylightDifferenceSec;
  1681. double CurrentDifference;
  1682. long CurrentDifferenceSec;
  1683. double StandardDifference;
  1684. long StandardDifferenceSec;
  1685. double DaylightDifference;
  1686. long DaylightDifferenceSec;
  1687. SYSTEMTIME SystemStandardDate;
  1688. SYSTEMTIME SystemDaylightDate;
  1689. TDateTime StandardDate;
  1690. TDateTime DaylightDate;
  1691. UnicodeString StandardName;
  1692. UnicodeString DaylightName;
  1693. // This is actually global, not per-year
  1694. bool DaylightHack;
  1695. bool HasDST() const
  1696. {
  1697. // On some systems it occurs that StandardDate is unset, while
  1698. // DaylightDate is set. MSDN states that this is invalid and
  1699. // should be treated as if there is no daylight saving.
  1700. // So check both.
  1701. return
  1702. (SystemStandardDate.wMonth != 0) &&
  1703. (SystemDaylightDate.wMonth != 0);
  1704. }
  1705. bool SummerDST() const
  1706. {
  1707. return HasDST() && (DaylightDate < StandardDate);
  1708. }
  1709. };
  1710. typedef std::map<int, TDateTimeParams> TYearlyDateTimeParams;
  1711. static TYearlyDateTimeParams YearlyDateTimeParams;
  1712. static std::unique_ptr<TCriticalSection> DateTimeParamsSection(TraceInitPtr(new TCriticalSection()));
  1713. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1714. TDateTime & Result);
  1715. //---------------------------------------------------------------------------
  1716. static unsigned short __fastcall DecodeYear(const TDateTime & DateTime)
  1717. {
  1718. unsigned short Year, Month, Day;
  1719. DecodeDate(DateTime, Year, Month, Day);
  1720. return Year;
  1721. }
  1722. //---------------------------------------------------------------------------
  1723. static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year)
  1724. {
  1725. TGuard Guard(DateTimeParamsSection.get());
  1726. TDateTimeParams * Result;
  1727. TYearlyDateTimeParams::iterator i = YearlyDateTimeParams.find(Year);
  1728. if (i != YearlyDateTimeParams.end())
  1729. {
  1730. Result = &(*i).second;
  1731. }
  1732. else
  1733. {
  1734. // creates new entry as a side effect
  1735. Result = &YearlyDateTimeParams[Year];
  1736. TIME_ZONE_INFORMATION TZI;
  1737. unsigned long GTZI;
  1738. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  1739. typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi);
  1740. TGetTimeZoneInformationForYear GetTimeZoneInformationForYear =
  1741. (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear");
  1742. if ((Year == 0) || (GetTimeZoneInformationForYear == NULL))
  1743. {
  1744. GTZI = GetTimeZoneInformation(&TZI);
  1745. }
  1746. else
  1747. {
  1748. GetTimeZoneInformationForYear(Year, NULL, &TZI);
  1749. GTZI = TIME_ZONE_ID_UNKNOWN;
  1750. }
  1751. switch (GTZI)
  1752. {
  1753. case TIME_ZONE_ID_UNKNOWN:
  1754. Result->CurrentDaylightDifferenceSec = 0;
  1755. break;
  1756. case TIME_ZONE_ID_STANDARD:
  1757. Result->CurrentDaylightDifferenceSec = TZI.StandardBias;
  1758. break;
  1759. case TIME_ZONE_ID_DAYLIGHT:
  1760. Result->CurrentDaylightDifferenceSec = TZI.DaylightBias;
  1761. break;
  1762. case TIME_ZONE_ID_INVALID:
  1763. default:
  1764. throw Exception(TIMEZONE_ERROR);
  1765. }
  1766. Result->BaseDifferenceSec = TZI.Bias;
  1767. Result->BaseDifference = double(TZI.Bias) / MinsPerDay;
  1768. Result->BaseDifferenceSec *= SecsPerMin;
  1769. Result->CurrentDifferenceSec = TZI.Bias +
  1770. Result->CurrentDaylightDifferenceSec;
  1771. Result->CurrentDifference =
  1772. double(Result->CurrentDifferenceSec) / MinsPerDay;
  1773. Result->CurrentDifferenceSec *= SecsPerMin;
  1774. Result->CurrentDaylightDifference =
  1775. double(Result->CurrentDaylightDifferenceSec) / MinsPerDay;
  1776. Result->CurrentDaylightDifferenceSec *= SecsPerMin;
  1777. Result->DaylightDifferenceSec = TZI.DaylightBias * SecsPerMin;
  1778. Result->DaylightDifference = double(TZI.DaylightBias) / MinsPerDay;
  1779. Result->StandardDifferenceSec = TZI.StandardBias * SecsPerMin;
  1780. Result->StandardDifference = double(TZI.StandardBias) / MinsPerDay;
  1781. Result->SystemStandardDate = TZI.StandardDate;
  1782. Result->SystemDaylightDate = TZI.DaylightDate;
  1783. unsigned short AYear = (Year != 0) ? Year : DecodeYear(Now());
  1784. if (Result->HasDST())
  1785. {
  1786. EncodeDSTMargin(Result->SystemStandardDate, AYear, Result->StandardDate);
  1787. EncodeDSTMargin(Result->SystemDaylightDate, AYear, Result->DaylightDate);
  1788. }
  1789. Result->StandardName = TZI.StandardName;
  1790. Result->DaylightName = TZI.DaylightName;
  1791. Result->DaylightHack = !IsWin7();
  1792. }
  1793. return Result;
  1794. }
  1795. //---------------------------------------------------------------------------
  1796. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1797. TDateTime & Result)
  1798. {
  1799. if (Date.wYear == 0)
  1800. {
  1801. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  1802. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  1803. (7 * (Date.wDay - 1));
  1804. // Day 5 means, the last occurence of day-of-week in month
  1805. if (Date.wDay == 5)
  1806. {
  1807. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  1808. if (Month > 12)
  1809. {
  1810. Month = static_cast<unsigned short>(Month - 12);
  1811. Year++;
  1812. }
  1813. if (Result >= EncodeDateVerbose(Year, Month, 1))
  1814. {
  1815. Result -= 7;
  1816. }
  1817. }
  1818. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  1819. Date.wMilliseconds);
  1820. }
  1821. else
  1822. {
  1823. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  1824. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  1825. }
  1826. }
  1827. //---------------------------------------------------------------------------
  1828. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  1829. {
  1830. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1831. bool Result;
  1832. // On some systems it occurs that StandardDate is unset, while
  1833. // DaylightDate is set. MSDN states that this is invalid and
  1834. // should be treated as if there is no daylight saving.
  1835. // So check both.
  1836. if (!Params->HasDST())
  1837. {
  1838. Result = false;
  1839. }
  1840. else
  1841. {
  1842. if (Params->SummerDST())
  1843. {
  1844. Result =
  1845. (DateTime >= Params->DaylightDate) &&
  1846. (DateTime < Params->StandardDate);
  1847. }
  1848. else
  1849. {
  1850. Result =
  1851. (DateTime < Params->StandardDate) ||
  1852. (DateTime >= Params->DaylightDate);
  1853. }
  1854. }
  1855. return Result;
  1856. }
  1857. //---------------------------------------------------------------------------
  1858. bool __fastcall UsesDaylightHack()
  1859. {
  1860. return GetDateTimeParams(0)->DaylightHack;
  1861. }
  1862. //---------------------------------------------------------------------------
  1863. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  1864. {
  1865. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1866. TDateTime Result = UnixDateDelta + (double(TimeStamp) / SecsPerDay);
  1867. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(Result));
  1868. if (Params->DaylightHack)
  1869. {
  1870. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1871. {
  1872. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1873. Result -= CurrentParams->CurrentDifference;
  1874. }
  1875. else if (DSTMode == dstmKeep)
  1876. {
  1877. Result -= Params->BaseDifference;
  1878. }
  1879. }
  1880. else
  1881. {
  1882. Result -= Params->BaseDifference;
  1883. }
  1884. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1885. {
  1886. Result -= DSTDifferenceForTime(Result);
  1887. }
  1888. return Result;
  1889. }
  1890. //---------------------------------------------------------------------------
  1891. __int64 __fastcall Round(double Number)
  1892. {
  1893. double Floor = floor(Number);
  1894. double Ceil = ceil(Number);
  1895. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1896. }
  1897. //---------------------------------------------------------------------------
  1898. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime, bool Add)
  1899. {
  1900. S = S.Trim();
  1901. int Index = 1;
  1902. if (SameText(S, L"today"))
  1903. {
  1904. S = L"0DS";
  1905. }
  1906. else if (SameText(S, L"yesterday"))
  1907. {
  1908. S = L"1DS";
  1909. }
  1910. while ((Index <= S.Length()) && IsDigit(S[Index]))
  1911. {
  1912. Index++;
  1913. }
  1914. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1915. int Number;
  1916. bool Result = TryStrToInt(NumberStr, Number);
  1917. if (Result)
  1918. {
  1919. if (!Add)
  1920. {
  1921. Number = -Number;
  1922. }
  1923. S.Delete(1, Index - 1);
  1924. S = S.Trim().UpperCase();
  1925. bool Start = (S.Length() == 2) && (S[2] == L'S');
  1926. if (Start)
  1927. {
  1928. S.SetLength(S.Length() - 1);
  1929. }
  1930. DateTime = Now();
  1931. // These may not overlap with ParseSize (K, M and G)
  1932. if (S == L"S")
  1933. {
  1934. DateTime = IncSecond(DateTime, Number);
  1935. if (Start)
  1936. {
  1937. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheSecond(DateTime)));
  1938. }
  1939. }
  1940. else if (S == L"N")
  1941. {
  1942. DateTime = IncMinute(DateTime, Number);
  1943. if (Start)
  1944. {
  1945. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheMinute(DateTime)));
  1946. }
  1947. }
  1948. else if (S == L"H")
  1949. {
  1950. DateTime = IncHour(DateTime, Number);
  1951. if (Start)
  1952. {
  1953. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheHour(DateTime)));
  1954. }
  1955. }
  1956. else if (S == L"D")
  1957. {
  1958. DateTime = IncDay(DateTime, Number);
  1959. if (Start)
  1960. {
  1961. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheDay(DateTime)));
  1962. }
  1963. }
  1964. else if (S == L"Y")
  1965. {
  1966. DateTime = IncYear(DateTime, Number);
  1967. if (Start)
  1968. {
  1969. DateTime = IncMilliSecond(DateTime, -MilliSecondOfTheYear(DateTime));
  1970. }
  1971. }
  1972. else
  1973. {
  1974. Result = false;
  1975. }
  1976. }
  1977. return Result;
  1978. }
  1979. //---------------------------------------------------------------------------
  1980. bool TryStrToDateTimeStandard(const UnicodeString & S, TDateTime & Value)
  1981. {
  1982. TFormatSettings FormatSettings = TFormatSettings::Create(GetDefaultLCID());
  1983. FormatSettings.DateSeparator = L'-';
  1984. FormatSettings.TimeSeparator = L':';
  1985. FormatSettings.ShortDateFormat = "yyyy/mm/dd";
  1986. FormatSettings.ShortTimeFormat = "hh:nn:ss";
  1987. return TryStrToDateTime(S, Value, FormatSettings);
  1988. }
  1989. //---------------------------------------------------------------------------
  1990. const wchar_t KiloSize = L'K';
  1991. const wchar_t MegaSize = L'M';
  1992. const wchar_t GigaSize = L'G';
  1993. //---------------------------------------------------------------------------
  1994. // Keep consistent with parse_blocksize
  1995. bool __fastcall TryStrToSize(UnicodeString SizeStr, __int64 & Size)
  1996. {
  1997. int Index = 0;
  1998. while ((Index + 1 <= SizeStr.Length()) && IsDigit(SizeStr[Index + 1]))
  1999. {
  2000. Index++;
  2001. }
  2002. bool Result =
  2003. (Index > 0) && TryStrToInt64(SizeStr.SubString(1, Index), Size);
  2004. if (Result)
  2005. {
  2006. SizeStr = SizeStr.SubString(Index + 1, SizeStr.Length() - Index).Trim();
  2007. if (!SizeStr.IsEmpty())
  2008. {
  2009. Result = (SizeStr.Length() == 1);
  2010. if (Result)
  2011. {
  2012. wchar_t Unit = towupper(SizeStr[1]);
  2013. switch (Unit)
  2014. {
  2015. case GigaSize:
  2016. Size *= 1024;
  2017. // fallthru
  2018. case MegaSize:
  2019. Size *= 1024;
  2020. // fallthru
  2021. case KiloSize:
  2022. Size *= 1024;
  2023. break;
  2024. default:
  2025. Result = false;
  2026. }
  2027. }
  2028. }
  2029. }
  2030. return Result;
  2031. }
  2032. //---------------------------------------------------------------------------
  2033. UnicodeString __fastcall SizeToStr(__int64 Size)
  2034. {
  2035. UnicodeString Result;
  2036. if ((Size <= 0) || ((Size % 1024) != 0))
  2037. {
  2038. Result = IntToStr(Size);
  2039. }
  2040. else
  2041. {
  2042. Size /= 1024;
  2043. if ((Size % 1024) != 0)
  2044. {
  2045. Result = IntToStr(Size) + KiloSize;
  2046. }
  2047. else
  2048. {
  2049. Size /= 1024;
  2050. if ((Size % 1024) != 0)
  2051. {
  2052. Result = IntToStr(Size) + MegaSize;
  2053. }
  2054. else
  2055. {
  2056. Size /= 1024;
  2057. Result = IntToStr(Size) + GigaSize;
  2058. }
  2059. }
  2060. }
  2061. return Result;
  2062. }
  2063. //---------------------------------------------------------------------------
  2064. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  2065. {
  2066. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2067. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  2068. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  2069. CurrentParams->CurrentDifferenceSec;
  2070. }
  2071. //---------------------------------------------------------------------------
  2072. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  2073. TDSTMode /*DSTMode*/)
  2074. {
  2075. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  2076. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2077. if (!Params->DaylightHack)
  2078. {
  2079. // We should probably use reversed code of FileTimeToDateTime here instead of custom implementation
  2080. // We are incrementing and decrementing BaseDifferenceSec because it
  2081. // can actually change between years
  2082. // (as it did in Belarus from GMT+2 to GMT+3 between 2011 and 2012)
  2083. UnixTimeStamp += (IsDateInDST(DateTime) ?
  2084. Params->DaylightDifferenceSec : Params->StandardDifferenceSec) +
  2085. Params->BaseDifferenceSec;
  2086. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2087. UnixTimeStamp -=
  2088. CurrentParams->CurrentDaylightDifferenceSec +
  2089. CurrentParams->BaseDifferenceSec;
  2090. }
  2091. FILETIME Result;
  2092. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  2093. return Result;
  2094. }
  2095. //---------------------------------------------------------------------------
  2096. // This can be replaced with TSearchRec.TimeStamp
  2097. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  2098. {
  2099. // duplicated in DirView.pas
  2100. TDateTime Result;
  2101. // The 0xFFF... is sometime seen for invalid timestamps,
  2102. // it would cause failure in SystemTimeToDateTime below
  2103. if (FileTime.dwLowDateTime == std::numeric_limits<DWORD>::max())
  2104. {
  2105. Result = MinDateTime;
  2106. }
  2107. else
  2108. {
  2109. SYSTEMTIME SysTime;
  2110. if (!UsesDaylightHack())
  2111. {
  2112. SYSTEMTIME UniverzalSysTime;
  2113. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  2114. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  2115. }
  2116. else
  2117. {
  2118. FILETIME LocalFileTime;
  2119. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  2120. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  2121. }
  2122. Result = SystemTimeToDateTimeVerbose(SysTime);
  2123. }
  2124. return Result;
  2125. }
  2126. //---------------------------------------------------------------------------
  2127. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  2128. TDSTMode DSTMode)
  2129. {
  2130. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  2131. if (UsesDaylightHack())
  2132. {
  2133. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  2134. {
  2135. FILETIME LocalFileTime;
  2136. SYSTEMTIME SystemTime;
  2137. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  2138. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  2139. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  2140. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2141. Result += (IsDateInDST(DateTime) ?
  2142. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  2143. if (DSTMode == dstmKeep)
  2144. {
  2145. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2146. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  2147. }
  2148. }
  2149. }
  2150. else
  2151. {
  2152. if (DSTMode == dstmWin)
  2153. {
  2154. FILETIME LocalFileTime;
  2155. SYSTEMTIME SystemTime;
  2156. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  2157. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  2158. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  2159. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2160. Result -= (IsDateInDST(DateTime) ?
  2161. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  2162. }
  2163. }
  2164. return Result;
  2165. }
  2166. //---------------------------------------------------------------------------
  2167. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  2168. {
  2169. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2170. DateTime += DSTDifferenceForTime(DateTime);
  2171. DateTime += Params->BaseDifference;
  2172. if (Params->DaylightHack)
  2173. {
  2174. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2175. DateTime += CurrentParams->CurrentDaylightDifference;
  2176. }
  2177. return DateTime;
  2178. }
  2179. //---------------------------------------------------------------------------
  2180. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  2181. {
  2182. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2183. DateTime -= DSTDifferenceForTime(DateTime);
  2184. DateTime -= Params->BaseDifference;
  2185. if (Params->DaylightHack)
  2186. {
  2187. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2188. DateTime -= CurrentParams->CurrentDaylightDifference;
  2189. }
  2190. return DateTime;
  2191. }
  2192. //---------------------------------------------------------------------------
  2193. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  2194. TDSTMode DSTMode)
  2195. {
  2196. __int64 Result;
  2197. if ((FileTime.dwLowDateTime == 0) &&
  2198. (FileTime.dwHighDateTime == 0))
  2199. {
  2200. Result = ::DateTimeToUnix(Now());
  2201. }
  2202. else
  2203. {
  2204. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  2205. }
  2206. return Result;
  2207. }
  2208. //---------------------------------------------------------------------------
  2209. double __fastcall DSTDifferenceForTime(TDateTime DateTime)
  2210. {
  2211. double Result;
  2212. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2213. if (IsDateInDST(DateTime))
  2214. {
  2215. Result = Params->DaylightDifference;
  2216. }
  2217. else
  2218. {
  2219. Result = Params->StandardDifference;
  2220. }
  2221. return Result;
  2222. }
  2223. //---------------------------------------------------------------------------
  2224. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  2225. {
  2226. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2227. if (Params->DaylightHack)
  2228. {
  2229. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  2230. {
  2231. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2232. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  2233. }
  2234. if (!IsDateInDST(DateTime))
  2235. {
  2236. if (DSTMode == dstmWin)
  2237. {
  2238. DateTime = DateTime - Params->DaylightDifference;
  2239. }
  2240. }
  2241. else
  2242. {
  2243. DateTime = DateTime - Params->StandardDifference;
  2244. }
  2245. }
  2246. else
  2247. {
  2248. if (DSTMode == dstmWin)
  2249. {
  2250. DateTime = DateTime + DSTDifferenceForTime(DateTime);
  2251. }
  2252. }
  2253. return DateTime;
  2254. }
  2255. //---------------------------------------------------------------------------
  2256. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  2257. {
  2258. UnicodeString Result = Format;
  2259. bool AsIs = false;
  2260. int Index = 1;
  2261. while (Index <= Result.Length())
  2262. {
  2263. wchar_t F = Result[Index];
  2264. if ((F == L'\'') || (F == L'\"'))
  2265. {
  2266. AsIs = !AsIs;
  2267. Index++;
  2268. }
  2269. else if (!AsIs && ((F == L'a') || (F == L'A')))
  2270. {
  2271. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  2272. {
  2273. Index += 5;
  2274. }
  2275. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  2276. {
  2277. Index += 3;
  2278. }
  2279. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  2280. {
  2281. Index += 4;
  2282. }
  2283. else
  2284. {
  2285. Index++;
  2286. }
  2287. }
  2288. else
  2289. {
  2290. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  2291. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  2292. {
  2293. Result.Insert(F, Index);
  2294. }
  2295. while ((Index <= Result.Length()) && (F == Result[Index]))
  2296. {
  2297. Index++;
  2298. }
  2299. }
  2300. }
  2301. return Result;
  2302. }
  2303. //---------------------------------------------------------------------------
  2304. UnicodeString __fastcall FormatTimeZone(long Sec)
  2305. {
  2306. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  2307. UnicodeString Str;
  2308. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  2309. {
  2310. Str = FORMAT(L"%d", (-Span.Hours));
  2311. }
  2312. else if (Span.Seconds == 0)
  2313. {
  2314. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  2315. }
  2316. else
  2317. {
  2318. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  2319. }
  2320. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  2321. return Str;
  2322. }
  2323. //---------------------------------------------------------------------------
  2324. UnicodeString __fastcall GetTimeZoneLogString()
  2325. {
  2326. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2327. UnicodeString Result =
  2328. FORMAT(L"Current: GMT%s", (FormatTimeZone(CurrentParams->CurrentDifferenceSec)));
  2329. if (!CurrentParams->HasDST())
  2330. {
  2331. Result += FORMAT(L" (%s), No DST", (CurrentParams->StandardName));
  2332. }
  2333. else
  2334. {
  2335. Result +=
  2336. FORMAT(L", Standard: GMT%s (%s), DST: GMT%s (%s), DST Start: %s, DST End: %s",
  2337. (FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->StandardDifferenceSec),
  2338. CurrentParams->StandardName,
  2339. FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->DaylightDifferenceSec),
  2340. CurrentParams->DaylightName,
  2341. CurrentParams->DaylightDate.DateString(),
  2342. CurrentParams->StandardDate.DateString()));
  2343. }
  2344. return Result;
  2345. }
  2346. //---------------------------------------------------------------------------
  2347. bool __fastcall AdjustClockForDSTEnabled()
  2348. {
  2349. // Windows XP deletes the DisableAutoDaylightTimeSet value when it is off
  2350. // (the later versions set it to DynamicDaylightTimeDisabled to 0)
  2351. bool DynamicDaylightTimeDisabled = false;
  2352. TRegistry * Registry = new TRegistry(KEY_READ);
  2353. try
  2354. {
  2355. Registry->RootKey = HKEY_LOCAL_MACHINE;
  2356. if (Registry->OpenKey(L"SYSTEM", false) &&
  2357. Registry->OpenKey(L"CurrentControlSet", false) &&
  2358. Registry->OpenKey(L"Control", false) &&
  2359. Registry->OpenKey(L"TimeZoneInformation", false))
  2360. {
  2361. if (Registry->ValueExists(L"DynamicDaylightTimeDisabled"))
  2362. {
  2363. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DynamicDaylightTimeDisabled");
  2364. }
  2365. // WORKAROUND
  2366. // Windows XP equivalent
  2367. else if (Registry->ValueExists(L"DisableAutoDaylightTimeSet"))
  2368. {
  2369. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DisableAutoDaylightTimeSet");
  2370. }
  2371. }
  2372. delete Registry;
  2373. }
  2374. catch(...)
  2375. {
  2376. }
  2377. return !DynamicDaylightTimeDisabled;
  2378. }
  2379. //---------------------------------------------------------------------------
  2380. UnicodeString __fastcall StandardDatestamp()
  2381. {
  2382. return FormatDateTime(L"yyyy'-'mm'-'dd", ConvertTimestampToUTC(Now()));
  2383. }
  2384. //---------------------------------------------------------------------------
  2385. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  2386. {
  2387. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  2388. }
  2389. //---------------------------------------------------------------------------
  2390. UnicodeString __fastcall StandardTimestamp()
  2391. {
  2392. return StandardTimestamp(Now());
  2393. }
  2394. //---------------------------------------------------------------------------
  2395. static TDateTime TwoSeconds(0, 0, 2, 0);
  2396. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  2397. {
  2398. // "FAT" time precision
  2399. // (when one time is seconds-precision and other is millisecond-precision,
  2400. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  2401. // be treated the same)
  2402. int Result;
  2403. if (T1 == T2)
  2404. {
  2405. // just optimization
  2406. Result = 0;
  2407. }
  2408. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  2409. {
  2410. Result = -1;
  2411. }
  2412. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  2413. {
  2414. Result = 1;
  2415. }
  2416. else
  2417. {
  2418. Result = 0;
  2419. }
  2420. return Result;
  2421. }
  2422. //---------------------------------------------------------------------------
  2423. int __fastcall TimeToMSec(TDateTime T)
  2424. {
  2425. return int(Round(double(T) * double(MSecsPerDay)));
  2426. }
  2427. //---------------------------------------------------------------------------
  2428. int __fastcall TimeToSeconds(TDateTime T)
  2429. {
  2430. return TimeToMSec(T) / MSecsPerSec;
  2431. }
  2432. //---------------------------------------------------------------------------
  2433. int __fastcall TimeToMinutes(TDateTime T)
  2434. {
  2435. return TimeToSeconds(T) / SecsPerMin;
  2436. }
  2437. //---------------------------------------------------------------------------
  2438. static bool __fastcall DoRecursiveDeleteFile(
  2439. const UnicodeString FileName, bool ToRecycleBin, UnicodeString & ErrorPath, int & Deleted)
  2440. {
  2441. bool Result;
  2442. Deleted = 0;
  2443. UnicodeString AErrorPath = FileName;
  2444. if (!ToRecycleBin)
  2445. {
  2446. TSearchRecChecked InitialSearchRec;
  2447. Result = FileSearchRec(FileName, InitialSearchRec);
  2448. if (Result)
  2449. {
  2450. if (!InitialSearchRec.IsDirectory())
  2451. {
  2452. Result = DeleteFile(ApiPath(FileName));
  2453. if (Result)
  2454. {
  2455. Deleted++;
  2456. }
  2457. }
  2458. else
  2459. {
  2460. TSearchRecOwned SearchRec;
  2461. Result = (FindFirstUnchecked(FileName + L"\\*", faAnyFile, SearchRec) == 0);
  2462. if (Result)
  2463. {
  2464. do
  2465. {
  2466. UnicodeString FileName2 = SearchRec.GetFilePath();
  2467. if (SearchRec.IsDirectory())
  2468. {
  2469. if (SearchRec.IsRealFile())
  2470. {
  2471. Result = DoRecursiveDeleteFile(FileName2, DebugAlwaysFalse(ToRecycleBin), AErrorPath, Deleted);
  2472. }
  2473. }
  2474. else
  2475. {
  2476. Result = DeleteFile(ApiPath(FileName2));
  2477. if (!Result)
  2478. {
  2479. AErrorPath = FileName2;
  2480. }
  2481. else
  2482. {
  2483. Deleted++;
  2484. }
  2485. }
  2486. }
  2487. while (Result && (FindNextUnchecked(SearchRec) == 0));
  2488. if (Result)
  2489. {
  2490. Result = RemoveDir(ApiPath(FileName));
  2491. if (Result)
  2492. {
  2493. Deleted++;
  2494. }
  2495. }
  2496. }
  2497. }
  2498. }
  2499. }
  2500. else
  2501. {
  2502. SHFILEOPSTRUCT Data;
  2503. memset(&Data, 0, sizeof(Data));
  2504. Data.hwnd = NULL;
  2505. Data.wFunc = FO_DELETE;
  2506. // SHFileOperation does not support long paths anyway
  2507. UnicodeString FileList(ApiPath(FileName));
  2508. FileList.SetLength(FileList.Length() + 2);
  2509. FileList[FileList.Length() - 1] = L'\0';
  2510. FileList[FileList.Length()] = L'\0';
  2511. Data.pFrom = FileList.c_str();
  2512. Data.pTo = L"\0\0"; // this will actually give one null more than needed
  2513. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  2514. FOF_NOERRORUI | FOF_SILENT;
  2515. if (DebugAlwaysTrue(ToRecycleBin))
  2516. {
  2517. Data.fFlags |= FOF_ALLOWUNDO;
  2518. }
  2519. int ErrorCode = SHFileOperation(&Data);
  2520. Result = (ErrorCode == 0);
  2521. if (!Result)
  2522. {
  2523. // according to MSDN, SHFileOperation may return following non-Win32
  2524. // error codes
  2525. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  2526. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  2527. (ErrorCode == 0x10074))
  2528. {
  2529. ErrorCode = 0;
  2530. }
  2531. SetLastError(ErrorCode);
  2532. }
  2533. if (Result)
  2534. {
  2535. Deleted = 1;
  2536. }
  2537. }
  2538. if (!Result)
  2539. {
  2540. ErrorPath = AErrorPath;
  2541. }
  2542. return Result;
  2543. }
  2544. //---------------------------------------------------------------------------
  2545. bool __fastcall RecursiveDeleteFile(const UnicodeString & FileName, bool ToRecycleBin)
  2546. {
  2547. UnicodeString ErrorPath; // unused
  2548. int Deleted;
  2549. bool Result = DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath, Deleted);
  2550. return Result;
  2551. }
  2552. //---------------------------------------------------------------------------
  2553. int __fastcall RecursiveDeleteFileChecked(const UnicodeString & FileName, bool ToRecycleBin)
  2554. {
  2555. UnicodeString ErrorPath;
  2556. int Deleted;
  2557. if (!DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath, Deleted))
  2558. {
  2559. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (ErrorPath)));
  2560. }
  2561. return Deleted;
  2562. }
  2563. //---------------------------------------------------------------------------
  2564. void __fastcall DeleteFileChecked(const UnicodeString & FileName)
  2565. {
  2566. if (!DeleteFile(ApiPath(FileName)))
  2567. {
  2568. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  2569. }
  2570. }
  2571. //---------------------------------------------------------------------------
  2572. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  2573. {
  2574. unsigned int Result;
  2575. if ((Answers & qaCancel) != 0)
  2576. {
  2577. Result = qaCancel;
  2578. }
  2579. else if ((Answers & qaNo) != 0)
  2580. {
  2581. Result = qaNo;
  2582. }
  2583. else if ((Answers & qaAbort) != 0)
  2584. {
  2585. Result = qaAbort;
  2586. }
  2587. else if ((Answers & qaOK) != 0)
  2588. {
  2589. Result = qaOK;
  2590. }
  2591. else
  2592. {
  2593. DebugFail();
  2594. Result = qaCancel;
  2595. }
  2596. return Result;
  2597. }
  2598. //---------------------------------------------------------------------------
  2599. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  2600. {
  2601. unsigned int Result;
  2602. if (FLAGSET(Answers, qaAbort))
  2603. {
  2604. Result = qaAbort;
  2605. }
  2606. else
  2607. {
  2608. Result = CancelAnswer(Answers);
  2609. }
  2610. return Result;
  2611. }
  2612. //---------------------------------------------------------------------------
  2613. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  2614. {
  2615. unsigned int Result;
  2616. if (FLAGSET(Answers, qaSkip))
  2617. {
  2618. Result = qaSkip;
  2619. }
  2620. else if (FLAGSET(Answers, qaIgnore))
  2621. {
  2622. Result = qaIgnore;
  2623. }
  2624. else if (FLAGSET(Answers, qaYes))
  2625. {
  2626. Result = qaYes;
  2627. }
  2628. else if (FLAGSET(Answers, qaOK))
  2629. {
  2630. Result = qaOK;
  2631. }
  2632. else if (FLAGSET(Answers, qaRetry))
  2633. {
  2634. Result = qaRetry;
  2635. }
  2636. else
  2637. {
  2638. Result = CancelAnswer(Answers);
  2639. }
  2640. return Result;
  2641. }
  2642. //---------------------------------------------------------------------------
  2643. TLibModule * __fastcall FindModule(void * Instance)
  2644. {
  2645. TLibModule * CurModule;
  2646. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  2647. while (CurModule)
  2648. {
  2649. if (CurModule->Instance == (unsigned)Instance)
  2650. {
  2651. break;
  2652. }
  2653. else
  2654. {
  2655. CurModule = CurModule->Next;
  2656. }
  2657. }
  2658. return CurModule;
  2659. }
  2660. //---------------------------------------------------------------------------
  2661. static UnicodeString __fastcall DoLoadStrFrom(HINSTANCE Module, int Ident, unsigned int MaxLength)
  2662. {
  2663. UnicodeString Result;
  2664. Result.SetLength(MaxLength);
  2665. int Length = LoadString(Module, Ident, Result.c_str(), MaxLength);
  2666. Result.SetLength(Length);
  2667. return Result;
  2668. }
  2669. //---------------------------------------------------------------------------
  2670. UnicodeString __fastcall LoadStrFrom(HINSTANCE Module, int Ident)
  2671. {
  2672. // 1024 = what VCL LoadStr limits the string to
  2673. return DoLoadStrFrom(Module, Ident, 1024);
  2674. }
  2675. //---------------------------------------------------------------------------
  2676. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  2677. {
  2678. TLibModule * MainModule = FindModule(HInstance);
  2679. DebugAssert(MainModule != NULL);
  2680. return DoLoadStrFrom((HINSTANCE)MainModule->ResInstance, Ident, MaxLength);
  2681. }
  2682. //---------------------------------------------------------------------------
  2683. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  2684. {
  2685. UnicodeString Result;
  2686. UnicodeString Str = LoadStr(Ident);
  2687. while (Part > 0)
  2688. {
  2689. Result = CutToChar(Str, L'|', false);
  2690. Part--;
  2691. }
  2692. return Result;
  2693. }
  2694. //---------------------------------------------------------------------------
  2695. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  2696. {
  2697. int i = 1;
  2698. while (i <= S.Length())
  2699. {
  2700. switch (S[i])
  2701. {
  2702. case L'+':
  2703. S[i] = ' ';
  2704. break;
  2705. case L'%':
  2706. {
  2707. UnicodeString Hex;
  2708. while ((i + 2 <= S.Length()) && (S[i] == L'%') &&
  2709. IsHex(S[i + 1]) && IsHex(S[i + 2]))
  2710. {
  2711. Hex += S.SubString(i + 1, 2);
  2712. S.Delete(i, 3);
  2713. }
  2714. if (!Hex.IsEmpty())
  2715. {
  2716. RawByteString Bytes = HexToBytes(Hex);
  2717. UnicodeString Chars(UTF8ToString(Bytes));
  2718. S.Insert(Chars, i);
  2719. i += Chars.Length() - 1;
  2720. }
  2721. }
  2722. break;
  2723. }
  2724. i++;
  2725. }
  2726. return S;
  2727. }
  2728. //---------------------------------------------------------------------------
  2729. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, const UnicodeString & DoNotEncode)
  2730. {
  2731. int Index = 1;
  2732. while (Index <= S.Length())
  2733. {
  2734. wchar_t C = S[Index];
  2735. if (IsLetter(C) ||
  2736. IsDigit(C) ||
  2737. (C == L'_') || (C == L'-') || (C == L'.') || (C == L'*') ||
  2738. (DoNotEncode.Pos(C) > 0))
  2739. {
  2740. Index++;
  2741. }
  2742. else
  2743. {
  2744. UTF8String UtfS(S.SubString(Index, 1));
  2745. UnicodeString H;
  2746. // BytesToHex with separator would do the same
  2747. for (int Index2 = 1; Index2 <= UtfS.Length(); Index2++)
  2748. {
  2749. H += L"%" + ByteToHex(static_cast<unsigned char>(UtfS[Index2]));
  2750. }
  2751. S.Delete(Index, 1);
  2752. S.Insert(H, Index);
  2753. Index += H.Length();
  2754. }
  2755. }
  2756. return S;
  2757. }
  2758. //---------------------------------------------------------------------------
  2759. UnicodeString __fastcall EncodeUrlString(UnicodeString S)
  2760. {
  2761. return DoEncodeUrl(S, UnicodeString());
  2762. }
  2763. //---------------------------------------------------------------------------
  2764. UnicodeString __fastcall EncodeUrlPath(UnicodeString S)
  2765. {
  2766. return DoEncodeUrl(S, L"/");
  2767. }
  2768. //---------------------------------------------------------------------------
  2769. UnicodeString __fastcall AppendUrlParams(UnicodeString AURL, UnicodeString Params)
  2770. {
  2771. // see also TWebHelpSystem::ShowHelp
  2772. const wchar_t FragmentSeparator = L'#';
  2773. UnicodeString URL = CutToChar(AURL, FragmentSeparator, false);
  2774. if (URL.Pos(L"?") == 0)
  2775. {
  2776. URL += L"?";
  2777. }
  2778. else
  2779. {
  2780. URL += L"&";
  2781. }
  2782. URL += Params;
  2783. AddToList(URL, AURL, FragmentSeparator);
  2784. return URL;
  2785. }
  2786. //---------------------------------------------------------------------------
  2787. UnicodeString __fastcall ExtractFileNameFromUrl(const UnicodeString & Url)
  2788. {
  2789. UnicodeString Result = Url;
  2790. int P = Result.Pos(L"?");
  2791. if (P > 0)
  2792. {
  2793. Result.SetLength(P - 1);
  2794. }
  2795. P = Result.LastDelimiter("/");
  2796. if (DebugAlwaysTrue(P > 0))
  2797. {
  2798. Result.Delete(1, P);
  2799. }
  2800. return Result;
  2801. }
  2802. //---------------------------------------------------------------------
  2803. bool IsDomainOrSubdomain(const UnicodeString & FullDomain, const UnicodeString & Domain)
  2804. {
  2805. return
  2806. SameText(FullDomain, Domain) ||
  2807. EndsText(L"." + Domain, FullDomain);
  2808. }
  2809. //---------------------------------------------------------------------------
  2810. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  2811. {
  2812. return ReplaceStr(Caption, L"&", L"&&");
  2813. }
  2814. //---------------------------------------------------------------------------
  2815. // duplicated in console's Main.cpp
  2816. static bool __fastcall DoCutToken(UnicodeString & Str, UnicodeString & Token,
  2817. UnicodeString * RawToken, UnicodeString * Separator, bool EscapeQuotesInQuotesOnly)
  2818. {
  2819. bool Result;
  2820. Token = L"";
  2821. // inspired by Putty's sftp_getcmd() from PSFTP.C
  2822. int Index = 1;
  2823. while ((Index <= Str.Length()) &&
  2824. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2825. {
  2826. Index++;
  2827. }
  2828. if (Index <= Str.Length())
  2829. {
  2830. bool Quoting = false;
  2831. while (Index <= Str.Length())
  2832. {
  2833. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2834. {
  2835. break;
  2836. }
  2837. // With EscapeQuotesInQuotesOnly we escape quotes only within quotes
  2838. // otherwise the "" means " (quote), but it should mean empty string.
  2839. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  2840. (Str[Index + 1] == L'"') && (!EscapeQuotesInQuotesOnly || Quoting))
  2841. {
  2842. Index += 2;
  2843. Token += L'"';
  2844. }
  2845. else if (Str[Index] == L'"')
  2846. {
  2847. Index++;
  2848. Quoting = !Quoting;
  2849. }
  2850. else
  2851. {
  2852. Token += Str[Index];
  2853. Index++;
  2854. }
  2855. }
  2856. if (RawToken != NULL)
  2857. {
  2858. (*RawToken) = Str.SubString(1, Index - 1);
  2859. }
  2860. if (Index <= Str.Length())
  2861. {
  2862. if (Separator != NULL)
  2863. {
  2864. *Separator = Str.SubString(Index, 1);
  2865. }
  2866. Index++;
  2867. }
  2868. else
  2869. {
  2870. if (Separator != NULL)
  2871. {
  2872. *Separator = UnicodeString();
  2873. }
  2874. }
  2875. Str = Str.SubString(Index, Str.Length());
  2876. Result = true;
  2877. }
  2878. else
  2879. {
  2880. Result = false;
  2881. Str = L"";
  2882. }
  2883. return Result;
  2884. }
  2885. //---------------------------------------------------------------------------
  2886. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  2887. UnicodeString * RawToken, UnicodeString * Separator)
  2888. {
  2889. return DoCutToken(Str, Token, RawToken, Separator, false);
  2890. }
  2891. //---------------------------------------------------------------------------
  2892. bool __fastcall CutTokenEx(UnicodeString & Str, UnicodeString & Token,
  2893. UnicodeString * RawToken, UnicodeString * Separator)
  2894. {
  2895. return DoCutToken(Str, Token, RawToken, Separator, true);
  2896. }
  2897. //---------------------------------------------------------------------------
  2898. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  2899. {
  2900. if (!Value.IsEmpty())
  2901. {
  2902. if (!List.IsEmpty() &&
  2903. ((List.Length() < Delimiter.Length()) ||
  2904. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  2905. {
  2906. List += Delimiter;
  2907. }
  2908. List += Value;
  2909. }
  2910. }
  2911. //---------------------------------------------------------------------------
  2912. void AddToShellFileListCommandLine(UnicodeString & List, const UnicodeString & Value)
  2913. {
  2914. UnicodeString Arg = ShellQuoteStr(Value);
  2915. AddToList(List, Arg, L" ");
  2916. }
  2917. //---------------------------------------------------------------------------
  2918. bool __fastcall IsWinVista()
  2919. {
  2920. // Vista is 6.0
  2921. // Win XP is 5.1
  2922. // There also 5.2, what is Windows 2003 or Windows XP 64bit
  2923. // (we consider it WinXP for now)
  2924. return CheckWin32Version(6, 0);
  2925. }
  2926. //---------------------------------------------------------------------------
  2927. bool __fastcall IsWin7()
  2928. {
  2929. return CheckWin32Version(6, 1);
  2930. }
  2931. //---------------------------------------------------------------------------
  2932. bool __fastcall IsWin8()
  2933. {
  2934. return CheckWin32Version(6, 2);
  2935. }
  2936. //---------------------------------------------------------------------------
  2937. bool __fastcall IsWin10()
  2938. {
  2939. return CheckWin32Version(10, 0);
  2940. }
  2941. //---------------------------------------------------------------------------
  2942. static OSVERSIONINFO __fastcall GetWindowsVersion()
  2943. {
  2944. OSVERSIONINFO Result;
  2945. memset(&Result, 0, sizeof(Result));
  2946. Result.dwOSVersionInfoSize = sizeof(Result);
  2947. // Cannot use the VCL Win32MajorVersion+Win32MinorVersion+Win32BuildNumber as
  2948. // on Windows 10 due to some hacking in InitPlatformId, the Win32BuildNumber is lost
  2949. GetVersionEx(&Result);
  2950. return Result;
  2951. }
  2952. //---------------------------------------------------------------------------
  2953. bool __fastcall IsWin10Build(unsigned int BuildNumber)
  2954. {
  2955. // It might be enough to check the dwBuildNumber, as we do in TWinConfiguration::IsDDExtBroken()
  2956. OSVERSIONINFO OSVersionInfo = GetWindowsVersion();
  2957. return
  2958. (OSVersionInfo.dwMajorVersion > 10) ||
  2959. ((OSVersionInfo.dwMajorVersion == 10) && (OSVersionInfo.dwMinorVersion > 0)) ||
  2960. ((OSVersionInfo.dwMajorVersion == 10) && (OSVersionInfo.dwMinorVersion == 0) &&
  2961. (OSVersionInfo.dwBuildNumber >= BuildNumber));
  2962. }
  2963. //---------------------------------------------------------------------------
  2964. bool IsWin11()
  2965. {
  2966. return IsWin10Build(22000);
  2967. }
  2968. //---------------------------------------------------------------------------
  2969. bool __fastcall IsWine()
  2970. {
  2971. HMODULE NtDll = GetModuleHandle(L"ntdll.dll");
  2972. return
  2973. DebugAlwaysTrue(NtDll != NULL) &&
  2974. (GetProcAddress(NtDll, "wine_get_version") != NULL);
  2975. }
  2976. //---------------------------------------------------------------------------
  2977. int GIsUWP = -1;
  2978. UnicodeString GPackageName;
  2979. //---------------------------------------------------------------------------
  2980. void EnableUWPTestMode()
  2981. {
  2982. GIsUWP = 1;
  2983. AppLog(L"UWP test mode");
  2984. }
  2985. //---------------------------------------------------------------------------
  2986. static void NeedUWPData()
  2987. {
  2988. if (GIsUWP < 0)
  2989. {
  2990. GIsUWP = 0;
  2991. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  2992. typedef LONG WINAPI (* GetCurrentPackageFamilyNameProc)(UINT32 * packageFamilyNameLength, PWSTR packageFamilyName);
  2993. GetCurrentPackageFamilyNameProc GetCurrentPackageFamilyName =
  2994. (GetCurrentPackageFamilyNameProc)GetProcAddress(Kernel32, "GetCurrentPackageFamilyName");
  2995. UINT32 NameLen = 0;
  2996. if ((GetCurrentPackageFamilyName != NULL) &&
  2997. (GetCurrentPackageFamilyName(&NameLen, NULL) == ERROR_INSUFFICIENT_BUFFER))
  2998. {
  2999. GIsUWP = 1;
  3000. AppLog(L"Is UWP application");
  3001. GPackageName.SetLength(NameLen);
  3002. if (GetCurrentPackageFamilyName(&NameLen, GPackageName.c_str()) == ERROR_SUCCESS)
  3003. {
  3004. PackStr(GPackageName);
  3005. }
  3006. else
  3007. {
  3008. GPackageName = L"err";
  3009. }
  3010. AppLogFmt(L"Package name: %s", (GPackageName));
  3011. }
  3012. else
  3013. {
  3014. AppLog(L"Is not UWP application");
  3015. }
  3016. }
  3017. }
  3018. //---------------------------------------------------------------------------
  3019. bool __fastcall IsUWP()
  3020. {
  3021. NeedUWPData();
  3022. return (GIsUWP > 0);
  3023. }
  3024. //---------------------------------------------------------------------------
  3025. UnicodeString GetPackageName()
  3026. {
  3027. NeedUWPData();
  3028. return GPackageName;
  3029. }
  3030. //---------------------------------------------------------------------------
  3031. bool IsOfficialPackage()
  3032. {
  3033. return (GetPackageName() == OfficialPackage);
  3034. }
  3035. //---------------------------------------------------------------------------
  3036. LCID __fastcall GetDefaultLCID()
  3037. {
  3038. return GetUserDefaultLCID();
  3039. }
  3040. //---------------------------------------------------------------------------
  3041. static UnicodeString ADefaultEncodingName;
  3042. UnicodeString __fastcall DefaultEncodingName()
  3043. {
  3044. if (ADefaultEncodingName.IsEmpty())
  3045. {
  3046. CPINFOEX Info;
  3047. GetCPInfoEx(CP_ACP, 0, &Info);
  3048. ADefaultEncodingName = Info.CodePageName;
  3049. }
  3050. return ADefaultEncodingName;
  3051. }
  3052. //---------------------------------------------------------------------------
  3053. bool _fastcall GetWindowsProductType(DWORD & Type)
  3054. {
  3055. bool Result;
  3056. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  3057. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  3058. TGetProductInfo GetProductInfo =
  3059. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  3060. if (GetProductInfo == NULL)
  3061. {
  3062. Result = false;
  3063. }
  3064. else
  3065. {
  3066. GetProductInfo(Win32MajorVersion(), Win32MinorVersion(), 0, 0, &Type);
  3067. Result = true;
  3068. }
  3069. return Result;
  3070. }
  3071. //---------------------------------------------------------------------------
  3072. UnicodeString __fastcall WindowsProductName()
  3073. {
  3074. UnicodeString Result;
  3075. TRegistry * Registry = new TRegistry(KEY_READ);
  3076. try
  3077. {
  3078. Registry->RootKey = HKEY_LOCAL_MACHINE;
  3079. if (Registry->OpenKey(L"SOFTWARE", false) &&
  3080. Registry->OpenKey(L"Microsoft", false) &&
  3081. Registry->OpenKey(L"Windows NT", false) &&
  3082. Registry->OpenKey(L"CurrentVersion", false))
  3083. {
  3084. Result = Registry->ReadString(L"ProductName");
  3085. }
  3086. delete Registry;
  3087. }
  3088. catch(...)
  3089. {
  3090. }
  3091. return Result;
  3092. }
  3093. //---------------------------------------------------------------------------
  3094. int __fastcall GetWindowsBuild()
  3095. {
  3096. return GetWindowsVersion().dwBuildNumber;
  3097. }
  3098. //---------------------------------------------------------------------------
  3099. UnicodeString __fastcall WindowsVersion()
  3100. {
  3101. OSVERSIONINFO OSVersionInfo = GetWindowsVersion();
  3102. UnicodeString Result = FORMAT(L"%d.%d.%d", (int(OSVersionInfo.dwMajorVersion), int(OSVersionInfo.dwMinorVersion), int(OSVersionInfo.dwBuildNumber)));
  3103. return Result;
  3104. }
  3105. //---------------------------------------------------------------------------
  3106. UnicodeString __fastcall WindowsVersionLong()
  3107. {
  3108. UnicodeString Result = WindowsVersion();
  3109. AddToList(Result, Win32CSDVersion(), L" ");
  3110. return Result;
  3111. }
  3112. //---------------------------------------------------------------------------
  3113. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  3114. {
  3115. UnicodeString FileName =
  3116. IncludeTrailingPathDelimiter(Path) +
  3117. FORMAT(L"wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  3118. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  3119. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  3120. bool Result = (Handle != INVALID_HANDLE_VALUE);
  3121. if (Result)
  3122. {
  3123. CloseHandle(Handle);
  3124. }
  3125. return Result;
  3126. }
  3127. //---------------------------------------------------------------------------
  3128. UnicodeString __fastcall FormatNumber(__int64 Number)
  3129. {
  3130. return FormatFloat(L"#,##0", Number);
  3131. }
  3132. //---------------------------------------------------------------------------
  3133. // simple alternative to FormatBytes
  3134. UnicodeString __fastcall FormatSize(__int64 Size)
  3135. {
  3136. return FormatNumber(Size);
  3137. }
  3138. //---------------------------------------------------------------------------
  3139. UnicodeString FormatDateTimeSpan(const TDateTime & DateTime)
  3140. {
  3141. UnicodeString Result;
  3142. if ((0 <= DateTime) && (DateTime <= MaxDateTime))
  3143. {
  3144. TTimeStamp TimeStamp = DateTimeToTimeStamp(DateTime);
  3145. int Days = TimeStamp.Date - DateDelta;
  3146. if (abs(Days) >= 4)
  3147. {
  3148. Result = FMTLOAD(DAYS_SPAN, (Days));
  3149. }
  3150. else
  3151. {
  3152. unsigned short Hour, Min, Sec, Dummy;
  3153. DecodeTime(DateTime, Hour, Min, Sec, Dummy);
  3154. int TotalHours = static_cast<int>(Hour) + (Days * HoursPerDay);
  3155. Result = FORMAT(L"%d%s%.2d%s%.2d", (TotalHours, FormatSettings.TimeSeparator, Min, FormatSettings.TimeSeparator, Sec));
  3156. }
  3157. }
  3158. return Result;
  3159. }
  3160. //---------------------------------------------------------------------------
  3161. UnicodeString FormatRelativeTime(const TDateTime & ANow, const TDateTime & AThen, bool DateOnly)
  3162. {
  3163. UnicodeString Result;
  3164. if (DateOnly)
  3165. {
  3166. if (IsSameDay(AThen, ANow - 1))
  3167. {
  3168. Result = LoadStrPart(TIME_RELATIVE, 3);
  3169. }
  3170. else if (IsSameDay(AThen, ANow))
  3171. {
  3172. Result = LoadStrPart(TIME_RELATIVE, 2);
  3173. }
  3174. }
  3175. if (Result.IsEmpty())
  3176. {
  3177. int Part, Num;
  3178. Num = YearsBetween(ANow, AThen);
  3179. if (Num > 1)
  3180. {
  3181. Part = 18;
  3182. }
  3183. else if (Num == 1)
  3184. {
  3185. Part = 17;
  3186. }
  3187. else
  3188. {
  3189. Num = MonthsBetween(ANow, AThen);
  3190. if (Num > 1)
  3191. {
  3192. Part = 16;
  3193. }
  3194. else if (Num == 1)
  3195. {
  3196. Part = 15;
  3197. }
  3198. else
  3199. {
  3200. Num = DaysBetween(ANow, AThen);
  3201. if (Num > 1)
  3202. {
  3203. Part = 12;
  3204. }
  3205. else if (Num == 1)
  3206. {
  3207. Part = 11;
  3208. }
  3209. else
  3210. {
  3211. Num = static_cast<int>(HoursBetween(ANow, AThen));
  3212. if (Num > 1)
  3213. {
  3214. Part = 10;
  3215. }
  3216. else if (Num == 1)
  3217. {
  3218. Part = 9;
  3219. }
  3220. else
  3221. {
  3222. Num = static_cast<int>(MinutesBetween(ANow, AThen));
  3223. if (Num > 1)
  3224. {
  3225. Part = 8;
  3226. }
  3227. else if (Num == 1)
  3228. {
  3229. Part = 7;
  3230. }
  3231. else
  3232. {
  3233. Num = static_cast<int>(SecondsBetween(ANow, AThen));
  3234. if (Num > 1)
  3235. {
  3236. Part = 6;
  3237. }
  3238. else if (Num == 1)
  3239. {
  3240. Part = 5;
  3241. }
  3242. else if (Num == 0)
  3243. {
  3244. Part = 1;
  3245. }
  3246. else
  3247. {
  3248. DebugFail();
  3249. Part = -1;
  3250. }
  3251. }
  3252. }
  3253. }
  3254. }
  3255. }
  3256. if (DebugAlwaysTrue(Part >= 0))
  3257. {
  3258. Result = FORMAT(LoadStrPart(TIME_RELATIVE, Part), (abs(Num)));
  3259. }
  3260. else
  3261. {
  3262. Result = FormatDateTime(L"ddddd", AThen);
  3263. }
  3264. }
  3265. return Result;
  3266. }
  3267. //---------------------------------------------------------------------------
  3268. UnicodeString __fastcall ExtractFileBaseName(const UnicodeString & Path)
  3269. {
  3270. return ChangeFileExt(ExtractFileName(Path), L"");
  3271. }
  3272. //---------------------------------------------------------------------------
  3273. TStringList * __fastcall TextToStringList(const UnicodeString & Text)
  3274. {
  3275. std::unique_ptr<TStringList> List(new TStringList());
  3276. List->Text = Text;
  3277. return List.release();
  3278. }
  3279. //---------------------------------------------------------------------------
  3280. UnicodeString __fastcall StringsToText(TStrings * Strings)
  3281. {
  3282. UnicodeString Result;
  3283. if (Strings->Count == 1)
  3284. {
  3285. Result = Strings->Strings[0];
  3286. }
  3287. else
  3288. {
  3289. Result = Strings->Text;
  3290. }
  3291. return Result;
  3292. }
  3293. //---------------------------------------------------------------------------
  3294. TStringList * __fastcall CommaTextToStringList(const UnicodeString & CommaText)
  3295. {
  3296. std::unique_ptr<TStringList> List(new TStringList());
  3297. List->CommaText = CommaText;
  3298. return List.release();
  3299. }
  3300. //---------------------------------------------------------------------------
  3301. TStrings * __fastcall CloneStrings(TStrings * Strings)
  3302. {
  3303. std::unique_ptr<TStringList> List(new TStringList());
  3304. List->AddStrings(Strings);
  3305. return List.release();
  3306. }
  3307. //---------------------------------------------------------------------------
  3308. UnicodeString __fastcall TrimVersion(UnicodeString Version)
  3309. {
  3310. while ((Version.Pos(L".") != Version.LastDelimiter(L".")) &&
  3311. (Version.SubString(Version.Length() - 1, 2) == L".0"))
  3312. {
  3313. Version.SetLength(Version.Length() - 2);
  3314. }
  3315. return Version;
  3316. }
  3317. //---------------------------------------------------------------------------
  3318. UnicodeString __fastcall FormatVersion(int MajovVersion, int MinorVersion, int Release)
  3319. {
  3320. return
  3321. TrimVersion(FORMAT(L"%d.%d.%d",
  3322. (MajovVersion, MinorVersion, Release)));
  3323. }
  3324. //---------------------------------------------------------------------------
  3325. TFormatSettings __fastcall GetEngFormatSettings()
  3326. {
  3327. return TFormatSettings::Create((TLocaleID)1033);
  3328. }
  3329. //---------------------------------------------------------------------------
  3330. int __fastcall ParseShortEngMonthName(const UnicodeString & MonthStr)
  3331. {
  3332. TFormatSettings FormatSettings = GetEngFormatSettings();
  3333. return IndexStr(MonthStr, FormatSettings.ShortMonthNames, FormatSettings.ShortMonthNames.Size()) + 1;
  3334. }
  3335. //---------------------------------------------------------------------------
  3336. TStringList * __fastcall CreateSortedStringList(bool CaseSensitive, System::Types::TDuplicates Duplicates)
  3337. {
  3338. TStringList * Result = new TStringList();
  3339. Result->CaseSensitive = CaseSensitive;
  3340. Result->Sorted = true;
  3341. Result->Duplicates = Duplicates;
  3342. return Result;
  3343. }
  3344. //---------------------------------------------------------------------------
  3345. bool SameIdent(const UnicodeString & Ident1, const UnicodeString & Ident2)
  3346. {
  3347. const UnicodeString Dash(L"-");
  3348. return SameText(ReplaceStr(Ident1, Dash, EmptyStr), ReplaceStr(Ident2, Dash, EmptyStr));
  3349. }
  3350. //---------------------------------------------------------------------------
  3351. UnicodeString __fastcall FindIdent(const UnicodeString & Ident, TStrings * Idents)
  3352. {
  3353. for (int Index = 0; Index < Idents->Count; Index++)
  3354. {
  3355. if (SameIdent(Ident, Idents->Strings[Index]))
  3356. {
  3357. return Idents->Strings[Index];
  3358. }
  3359. }
  3360. return Ident;
  3361. }
  3362. //---------------------------------------------------------------------------
  3363. UnicodeString GetTlsErrorStr(unsigned long Err)
  3364. {
  3365. char Buffer[512];
  3366. ERR_error_string_n(Err, Buffer, sizeof(Buffer));
  3367. UnicodeString S = UnicodeString(UTF8String(Buffer));
  3368. for (int I = 0; I < 4; I++)
  3369. {
  3370. CutToChar(S, L':', false);
  3371. }
  3372. UnicodeString ErrStr = IntToHex(static_cast<unsigned int>(Err));
  3373. return FORMAT(L"OpenSSL %s: %s", (ErrStr, S.TrimRight()));
  3374. }
  3375. //---------------------------------------------------------------------------
  3376. UnicodeString GetTlsErrorStrs()
  3377. {
  3378. UnicodeString Result;
  3379. int Error;
  3380. const char * Data;
  3381. while ((Error = ERR_get_error_all(NULL, NULL, NULL, &Data, NULL)) != 0)
  3382. {
  3383. UnicodeString S = GetTlsErrorStr(Error);
  3384. if ((Data != NULL) && (strlen(Data) > 0))
  3385. {
  3386. UnicodeString DataStr = UnicodeString(UTF8String(Data)).TrimRight();
  3387. S += FORMAT(L" (%s)", (DataStr));
  3388. }
  3389. AddToList(Result, S, L"\n");
  3390. }
  3391. return Result;
  3392. }
  3393. //---------------------------------------------------------------------------
  3394. static FILE * __fastcall OpenCertificate(const UnicodeString & Path)
  3395. {
  3396. FILE * Result = _wfopen(ApiPath(Path).c_str(), L"rb");
  3397. if (Result == NULL)
  3398. {
  3399. int Error = errno;
  3400. throw EOSExtException(MainInstructions(FMTLOAD(CERTIFICATE_OPEN_ERROR, (Path))), Error);
  3401. }
  3402. return Result;
  3403. }
  3404. //---------------------------------------------------------------------------
  3405. struct TPemPasswordCallbackData
  3406. {
  3407. UnicodeString * Passphrase;
  3408. };
  3409. //---------------------------------------------------------------------------
  3410. static int PemPasswordCallback(char * Buf, int Size, int /*RWFlag*/, void * UserData)
  3411. {
  3412. TPemPasswordCallbackData & Data = *reinterpret_cast<TPemPasswordCallbackData *>(UserData);
  3413. UTF8String UtfPassphrase = UTF8String(*Data.Passphrase);
  3414. strncpy(Buf, UtfPassphrase.c_str(), Size);
  3415. Shred(UtfPassphrase);
  3416. Buf[Size - 1] = '\0';
  3417. return strlen(Buf);
  3418. }
  3419. //---------------------------------------------------------------------------
  3420. static bool __fastcall IsTlsPassphraseError(unsigned long Error, bool HasPassphrase)
  3421. {
  3422. int ErrorLib = ERR_GET_LIB(Error);
  3423. int ErrorReason = ERR_GET_REASON(Error);
  3424. bool Result =
  3425. ((ErrorLib == ERR_LIB_PKCS12) &&
  3426. (ErrorReason == PKCS12_R_MAC_VERIFY_FAILURE)) ||
  3427. ((ErrorLib == ERR_LIB_PEM) &&
  3428. (ErrorReason == PEM_R_BAD_PASSWORD_READ)) ||
  3429. (HasPassphrase && (ERR_LIB_EVP == ERR_LIB_EVP) &&
  3430. ((ErrorReason == PEM_R_BAD_DECRYPT) || (ErrorReason == PEM_R_BAD_BASE64_DECODE)));
  3431. return Result;
  3432. }
  3433. //---------------------------------------------------------------------------
  3434. static void __fastcall ThrowTlsCertificateErrorIgnorePassphraseErrors(const UnicodeString & Path, bool HasPassphrase)
  3435. {
  3436. unsigned long Error = ERR_get_error();
  3437. if (!IsTlsPassphraseError(Error, HasPassphrase))
  3438. {
  3439. throw ExtException(MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (Path))), GetTlsErrorStr(Error));
  3440. }
  3441. }
  3442. //---------------------------------------------------------------------------
  3443. void __fastcall ParseCertificate(const UnicodeString & Path,
  3444. const UnicodeString & Passphrase, X509 *& Certificate, EVP_PKEY *& PrivateKey,
  3445. bool & WrongPassphrase)
  3446. {
  3447. Certificate = NULL;
  3448. PrivateKey = NULL;
  3449. WrongPassphrase = false;
  3450. bool HasPassphrase = !Passphrase.IsEmpty();
  3451. FILE * File;
  3452. // Inspired by neon's ne_ssl_clicert_read
  3453. File = OpenCertificate(Path);
  3454. // openssl pkcs12 -inkey cert.pem -in cert.crt -export -out cert.pfx
  3455. // Binary file
  3456. PKCS12 * Pkcs12 = d2i_PKCS12_fp(File, NULL);
  3457. fclose(File);
  3458. if (Pkcs12 != NULL)
  3459. {
  3460. UTF8String PassphraseUtf(Passphrase);
  3461. bool Result =
  3462. (PKCS12_parse(Pkcs12, PassphraseUtf.c_str(), &PrivateKey, &Certificate, NULL) == 1);
  3463. PKCS12_free(Pkcs12);
  3464. if (!Result)
  3465. {
  3466. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  3467. WrongPassphrase = true;
  3468. }
  3469. }
  3470. else
  3471. {
  3472. ERR_clear_error();
  3473. TPemPasswordCallbackData CallbackUserData;
  3474. // PemPasswordCallback never writes to the .Passphrase
  3475. CallbackUserData.Passphrase = const_cast<UnicodeString *>(&Passphrase);
  3476. File = OpenCertificate(Path);
  3477. // Encrypted:
  3478. // openssl req -x509 -newkey rsa:2048 -keyout cert.pem -out cert.crt
  3479. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  3480. // ...
  3481. // -----END ENCRYPTED PRIVATE KEY-----
  3482. // Not encrypted (add -nodes):
  3483. // -----BEGIN PRIVATE KEY-----
  3484. // ...
  3485. // -----END PRIVATE KEY-----
  3486. // Or (openssl genrsa -out client.key 1024 # used for certificate signing request)
  3487. // -----BEGIN RSA PRIVATE KEY-----
  3488. // ...
  3489. // -----END RSA PRIVATE KEY-----
  3490. PrivateKey = PEM_read_PrivateKey(File, NULL, PemPasswordCallback, &CallbackUserData);
  3491. fclose(File);
  3492. try
  3493. {
  3494. if (PrivateKey == NULL)
  3495. {
  3496. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  3497. WrongPassphrase = true;
  3498. }
  3499. File = OpenCertificate(Path);
  3500. // The file can contain both private and public key
  3501. // (basically cert.pem and cert.crt appended one to each other)
  3502. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  3503. // ...
  3504. // -----END ENCRYPTED PRIVATE KEY-----
  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. unsigned long Error = ERR_get_error();
  3513. // unlikely
  3514. if (IsTlsPassphraseError(Error, HasPassphrase))
  3515. {
  3516. WrongPassphrase = true;
  3517. }
  3518. else
  3519. {
  3520. UnicodeString CertificatePath = ChangeFileExt(Path, L".cer");
  3521. if (!FileExists(CertificatePath))
  3522. {
  3523. CertificatePath = ChangeFileExt(Path, L".crt");
  3524. }
  3525. if (!FileExists(CertificatePath))
  3526. {
  3527. throw Exception(MainInstructions(FMTLOAD(CERTIFICATE_PUBLIC_KEY_NOT_FOUND, (Path))));
  3528. }
  3529. else
  3530. {
  3531. File = OpenCertificate(CertificatePath);
  3532. // -----BEGIN CERTIFICATE-----
  3533. // ...
  3534. // -----END CERTIFICATE-----
  3535. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  3536. fclose(File);
  3537. if (Certificate == NULL)
  3538. {
  3539. unsigned long Base64Error = ERR_get_error();
  3540. File = OpenCertificate(CertificatePath);
  3541. // Binary DER-encoded certificate
  3542. // (as above, with BEGIN/END removed, and decoded from Base64 to binary)
  3543. // openssl x509 -in cert.crt -out client.der.crt -outform DER
  3544. Certificate = d2i_X509_fp(File, NULL);
  3545. fclose(File);
  3546. if (Certificate == NULL)
  3547. {
  3548. unsigned long DERError = ERR_get_error();
  3549. UnicodeString Message = MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (CertificatePath)));
  3550. UnicodeString MoreMessages =
  3551. FORMAT(L"Base64: %s\nDER: %s", (GetTlsErrorStr(Base64Error), GetTlsErrorStr(DERError)));
  3552. throw ExtException(Message, MoreMessages);
  3553. }
  3554. }
  3555. }
  3556. }
  3557. }
  3558. }
  3559. __finally
  3560. {
  3561. // We loaded private key, but failed to load certificate, discard the certificate
  3562. // (either exception was thrown or WrongPassphrase)
  3563. if ((PrivateKey != NULL) && (Certificate == NULL))
  3564. {
  3565. EVP_PKEY_free(PrivateKey);
  3566. PrivateKey = NULL;
  3567. }
  3568. // Certificate was verified, but passphrase was wrong when loading private key,
  3569. // so discard the certificate
  3570. else if ((Certificate != NULL) && (PrivateKey == NULL))
  3571. {
  3572. X509_free(Certificate);
  3573. Certificate = NULL;
  3574. }
  3575. }
  3576. }
  3577. }
  3578. //---------------------------------------------------------------------------
  3579. void __fastcall CheckCertificate(const UnicodeString & Path)
  3580. {
  3581. X509 * Certificate;
  3582. EVP_PKEY * PrivateKey;
  3583. bool WrongPassphrase;
  3584. ParseCertificate(Path, L"", Certificate, PrivateKey, WrongPassphrase);
  3585. if (PrivateKey != NULL)
  3586. {
  3587. EVP_PKEY_free(PrivateKey);
  3588. }
  3589. if (Certificate != NULL)
  3590. {
  3591. X509_free(Certificate);
  3592. }
  3593. }
  3594. //---------------------------------------------------------------------------
  3595. const UnicodeString HttpProtocol(L"http");
  3596. const UnicodeString HttpsProtocol(L"https");
  3597. const UnicodeString ProtocolSeparator(L"://");
  3598. //---------------------------------------------------------------------------
  3599. bool __fastcall IsHttpUrl(const UnicodeString & S)
  3600. {
  3601. return StartsText(HttpProtocol + ProtocolSeparator, S);
  3602. }
  3603. //---------------------------------------------------------------------------
  3604. bool __fastcall IsHttpOrHttpsUrl(const UnicodeString & S)
  3605. {
  3606. return
  3607. IsHttpUrl(S) ||
  3608. StartsText(HttpsProtocol + ProtocolSeparator, S);
  3609. }
  3610. //---------------------------------------------------------------------------
  3611. UnicodeString __fastcall ChangeUrlProtocol(const UnicodeString & S, const UnicodeString & Protocol)
  3612. {
  3613. int P = S.Pos(ProtocolSeparator);
  3614. DebugAssert(P > 0);
  3615. return Protocol + ProtocolSeparator + RightStr(S, S.Length() - P - ProtocolSeparator.Length() + 1);
  3616. }
  3617. //---------------------------------------------------------------------------
  3618. const UnicodeString RtfPara(TraceInitStr(L"\\par\n"));
  3619. const UnicodeString AssemblyNamespace(TraceInitStr(L"WinSCP"));
  3620. const UnicodeString TransferOptionsClassName(TraceInitStr(L"TransferOptions"));
  3621. const UnicodeString SessionClassName(TraceInitStr(L"Session"));
  3622. const UnicodeString RtfHyperlinkField(TraceInitStr(L"HYPERLINK"));
  3623. const UnicodeString RtfHyperlinkFieldPrefix(TraceInitStr(RtfHyperlinkField + L" \""));
  3624. const UnicodeString RtfHyperlinkFieldSuffix(TraceInitStr(L"\" "));
  3625. //---------------------------------------------------------------------
  3626. UnicodeString __fastcall RtfColor(int Index)
  3627. {
  3628. return FORMAT(L"\\cf%d", (Index));
  3629. }
  3630. //---------------------------------------------------------------------
  3631. UnicodeString __fastcall RtfText(const UnicodeString & Text, bool Rtf)
  3632. {
  3633. UnicodeString Result = Text;
  3634. if (Rtf)
  3635. {
  3636. int Index = 1;
  3637. while (Index <= Result.Length())
  3638. {
  3639. UnicodeString Replacement;
  3640. wchar_t Ch = Result[Index];
  3641. if ((Ch == L'\\') || (Ch == L'{') || (Ch == L'}'))
  3642. {
  3643. Replacement = FORMAT(L"\\%s", (Ch));
  3644. }
  3645. else if (Ch >= 0x0080)
  3646. {
  3647. Replacement = FORMAT(L"\\u%d?", (int(Ch)));
  3648. }
  3649. if (!Replacement.IsEmpty())
  3650. {
  3651. Result.Delete(Index, 1);
  3652. Result.Insert(Replacement, Index);
  3653. Index += Replacement.Length();
  3654. }
  3655. else
  3656. {
  3657. Index++;
  3658. }
  3659. }
  3660. }
  3661. return Result;
  3662. }
  3663. //---------------------------------------------------------------------
  3664. UnicodeString __fastcall RtfColorText(int Color, const UnicodeString & Text)
  3665. {
  3666. return RtfColor(Color) + L" " + RtfText(Text) + RtfColor(0) + L" ";
  3667. }
  3668. //---------------------------------------------------------------------
  3669. UnicodeString __fastcall RtfColorItalicText(int Color, const UnicodeString & Text)
  3670. {
  3671. return RtfColor(Color) + L"\\i " + RtfText(Text) + L"\\i0" + RtfColor(0) + L" ";
  3672. }
  3673. //---------------------------------------------------------------------
  3674. UnicodeString __fastcall RtfOverrideColorText(const UnicodeString & Text)
  3675. {
  3676. return RtfColorText(1, Text);
  3677. }
  3678. //---------------------------------------------------------------------
  3679. UnicodeString __fastcall RtfKeyword(const UnicodeString & Text)
  3680. {
  3681. return RtfColorText(5, Text);
  3682. }
  3683. //---------------------------------------------------------------------
  3684. UnicodeString __fastcall RtfParameter(const UnicodeString & Text)
  3685. {
  3686. return RtfColorText(6, Text);
  3687. }
  3688. //---------------------------------------------------------------------
  3689. UnicodeString __fastcall RtfString(const UnicodeString & Text)
  3690. {
  3691. return RtfColorText(4, Text);
  3692. }
  3693. //---------------------------------------------------------------------
  3694. UnicodeString __fastcall RtfLink(const UnicodeString & Link, const UnicodeString & RtfText)
  3695. {
  3696. return
  3697. L"{\\field{\\*\\fldinst{" + RtfHyperlinkFieldPrefix + Link + RtfHyperlinkFieldSuffix + L"}}{\\fldrslt{" +
  3698. RtfText + L"}}}";
  3699. }
  3700. //---------------------------------------------------------------------
  3701. UnicodeString __fastcall ScriptCommandLink(const UnicodeString & Command)
  3702. {
  3703. return L"scriptcommand_" + Command;
  3704. }
  3705. //---------------------------------------------------------------------
  3706. UnicodeString __fastcall RtfSwitch(
  3707. const UnicodeString & Switch, const UnicodeString & Link, bool Rtf)
  3708. {
  3709. UnicodeString Result = FORMAT(L"-%s", (Switch));
  3710. if (Rtf)
  3711. {
  3712. Result = RtfLink(Link + L"#" + Switch.LowerCase(), RtfParameter(Result));
  3713. }
  3714. return L" " + Result;
  3715. }
  3716. //---------------------------------------------------------------------
  3717. UnicodeString __fastcall RtfSwitchValue(
  3718. const UnicodeString & Name, const UnicodeString & Link, const UnicodeString & Value, bool Rtf)
  3719. {
  3720. return RtfSwitch(Name, Link, Rtf) + L"=" + Value;
  3721. }
  3722. //---------------------------------------------------------------------
  3723. UnicodeString __fastcall RtfSwitch(
  3724. const UnicodeString & Name, const UnicodeString & Link, const UnicodeString & Value, bool Rtf)
  3725. {
  3726. return RtfSwitchValue(Name, Link, RtfText(FORMAT("\"%s\"", (EscapeParam(Value))), Rtf), Rtf);
  3727. }
  3728. //---------------------------------------------------------------------
  3729. UnicodeString __fastcall RtfSwitch(
  3730. const UnicodeString & Name, const UnicodeString & Link, int Value, bool Rtf)
  3731. {
  3732. return RtfSwitchValue(Name, Link, RtfText(IntToStr(Value), Rtf), Rtf);
  3733. }
  3734. //---------------------------------------------------------------------
  3735. UnicodeString __fastcall RtfRemoveHyperlinks(UnicodeString Text)
  3736. {
  3737. // Remove all tags HYPERLINK "https://www.example.com".
  3738. // See also RtfEscapeParam
  3739. int Index = 1;
  3740. int P;
  3741. while ((P = PosEx(RtfHyperlinkFieldPrefix, Text, Index)) > 0)
  3742. {
  3743. int Index2 = P + RtfHyperlinkFieldPrefix.Length();
  3744. int P2 = PosEx(RtfHyperlinkFieldSuffix, Text, Index2);
  3745. if (P2 > 0)
  3746. {
  3747. Text.Delete(P, P2 - P + RtfHyperlinkFieldSuffix.Length());
  3748. }
  3749. else
  3750. {
  3751. Index = Index2;
  3752. }
  3753. }
  3754. return Text;
  3755. }
  3756. //---------------------------------------------------------------------
  3757. UnicodeString __fastcall RtfEscapeParam(UnicodeString Param, bool PowerShellEscape)
  3758. {
  3759. const UnicodeString Quote(L"\"");
  3760. UnicodeString Escape(Quote);
  3761. if (PowerShellEscape)
  3762. {
  3763. Escape = "`" + Escape + "`";
  3764. }
  3765. // Equivalent of EscapeParam, except that it does not double quotes in HYPERLINK.
  3766. // See also RtfRemoveHyperlinks.
  3767. int Index = 1;
  3768. while (true)
  3769. {
  3770. int P1 = PosEx(Quote, Param, Index);
  3771. if (P1 == 0)
  3772. {
  3773. // no more quotes
  3774. break;
  3775. }
  3776. else
  3777. {
  3778. int P2 = PosEx(RtfHyperlinkFieldPrefix, Param, Index);
  3779. int P3;
  3780. if ((P2 > 0) && (P2 < P1) && ((P3 = PosEx(RtfHyperlinkFieldSuffix, Param, P2)) > 0))
  3781. {
  3782. // skip HYPERLINK
  3783. Index = P3 + RtfHyperlinkFieldSuffix.Length();
  3784. }
  3785. else
  3786. {
  3787. Param.Insert(Escape, P1);
  3788. Index = P1 + (Escape.Length() + Quote.Length());
  3789. }
  3790. }
  3791. }
  3792. return Param;
  3793. }
  3794. //---------------------------------------------------------------------
  3795. static UnicodeString __fastcall RtfCodeComment(const UnicodeString & Text)
  3796. {
  3797. return RtfColorItalicText(2, Text);
  3798. }
  3799. //---------------------------------------------------------------------
  3800. UnicodeString __fastcall AssemblyCommentLine(TAssemblyLanguage Language, const UnicodeString & Text)
  3801. {
  3802. UnicodeString Prefix;
  3803. switch (Language)
  3804. {
  3805. case alCSharp:
  3806. Prefix = L"//";
  3807. break;
  3808. case alVBNET:
  3809. Prefix = L"'";
  3810. break;
  3811. case alPowerShell:
  3812. Prefix = L"#";
  3813. break;
  3814. }
  3815. return RtfCodeComment(Prefix + L" " + Text) + RtfPara;
  3816. }
  3817. //---------------------------------------------------------------------
  3818. UnicodeString __fastcall AssemblyString(TAssemblyLanguage Language, UnicodeString S)
  3819. {
  3820. switch (Language)
  3821. {
  3822. case alCSharp:
  3823. if (S.Pos(L"\\") > 0)
  3824. {
  3825. S = FORMAT(L"@\"%s\"", (ReplaceStr(S, L"\"", L"\"\"")));
  3826. }
  3827. else
  3828. {
  3829. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"\\\"")));
  3830. }
  3831. break;
  3832. case alVBNET:
  3833. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"\"\"")));
  3834. break;
  3835. case alPowerShell:
  3836. S = FORMAT(L"\"%s\"", (ReplaceStr(ReplaceStr(ReplaceStr(S, L"`", L"``"), L"$", L"`$"), L"\"", L"`\"")));
  3837. break;
  3838. default:
  3839. DebugFail();
  3840. break;
  3841. }
  3842. return RtfString(S);
  3843. }
  3844. //---------------------------------------------------------------------
  3845. static UnicodeString __fastcall RtfClass(const UnicodeString & Text)
  3846. {
  3847. return RtfColorText(3, Text);
  3848. }
  3849. //---------------------------------------------------------------------
  3850. UnicodeString __fastcall RtfLibraryClass(const UnicodeString & ClassName)
  3851. {
  3852. return RtfLink(L"library_" + ClassName.LowerCase(), RtfClass(ClassName));
  3853. }
  3854. //---------------------------------------------------------------------
  3855. UnicodeString __fastcall RtfLibraryMethod(const UnicodeString & ClassName, const UnicodeString & MethodName, bool InPage)
  3856. {
  3857. return RtfLink(L"library_" + ClassName.LowerCase() + (InPage ? L"#" : L"_") + MethodName.LowerCase(), RtfOverrideColorText(MethodName));
  3858. }
  3859. //---------------------------------------------------------------------
  3860. static UnicodeString __fastcall RtfLibraryProperty(const UnicodeString & ClassName, const UnicodeString & PropertyName)
  3861. {
  3862. return RtfLink(L"library_" + ClassName.LowerCase() + L"#" + PropertyName.LowerCase(), RtfOverrideColorText(PropertyName));
  3863. }
  3864. //---------------------------------------------------------------------
  3865. UnicodeString __fastcall AssemblyVariableName(TAssemblyLanguage Language, const UnicodeString & ClassName)
  3866. {
  3867. UnicodeString Result = ClassName.SubString(1, 1).LowerCase() + ClassName.SubString(2, ClassName.Length() - 1);
  3868. if (Language == alPowerShell)
  3869. {
  3870. Result = L"$" + Result;
  3871. }
  3872. return Result;
  3873. }
  3874. //---------------------------------------------------------------------
  3875. UnicodeString __fastcall AssemblyStatementSeparator(TAssemblyLanguage Language)
  3876. {
  3877. UnicodeString Result;
  3878. switch (Language)
  3879. {
  3880. case alCSharp:
  3881. Result = L";";
  3882. break;
  3883. case alVBNET:
  3884. case alPowerShell:
  3885. // noop
  3886. break;
  3887. }
  3888. return Result;
  3889. }
  3890. //---------------------------------------------------------------------
  3891. UnicodeString __fastcall AssemblyPropertyRaw(
  3892. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name,
  3893. const UnicodeString & Value, bool Inline)
  3894. {
  3895. UnicodeString Result;
  3896. UnicodeString RtfPropertyAndValue = RtfLibraryProperty(ClassName, Name) + L" = " + Value;
  3897. UnicodeString Indetation = (Inline ? L"" : L" ");
  3898. UnicodeString SpaceOrPara = (Inline ? UnicodeString(L" ") : RtfPara);
  3899. switch (Language)
  3900. {
  3901. case alCSharp:
  3902. Result = Indetation + RtfPropertyAndValue + (Inline ? L"" : L",") + SpaceOrPara;
  3903. break;
  3904. case alVBNET:
  3905. Result = Indetation + L"." + RtfPropertyAndValue + SpaceOrPara;
  3906. break;
  3907. case alPowerShell:
  3908. Result = Indetation + RtfPropertyAndValue + SpaceOrPara;
  3909. break;
  3910. }
  3911. return Result;
  3912. }
  3913. //---------------------------------------------------------------------
  3914. UnicodeString __fastcall AssemblyProperty(
  3915. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name,
  3916. const UnicodeString & Type, const UnicodeString & Member, bool Inline)
  3917. {
  3918. UnicodeString PropertyValue;
  3919. switch (Language)
  3920. {
  3921. case alCSharp:
  3922. case alVBNET:
  3923. PropertyValue = RtfClass(Type) + RtfText(L"." + Member);
  3924. break;
  3925. case alPowerShell:
  3926. PropertyValue = RtfText(L"[" + AssemblyNamespace + L".") + RtfClass(Type) + RtfText(L"]::" + Member);
  3927. break;
  3928. }
  3929. return AssemblyPropertyRaw(Language, ClassName, Name, PropertyValue, Inline);
  3930. }
  3931. //---------------------------------------------------------------------
  3932. UnicodeString __fastcall AssemblyProperty(
  3933. TAssemblyLanguage Language, const UnicodeString & ClassName,
  3934. const UnicodeString & Name, const UnicodeString & Value, bool Inline)
  3935. {
  3936. return AssemblyPropertyRaw(Language, ClassName, Name, AssemblyString(Language, Value), Inline);
  3937. }
  3938. //---------------------------------------------------------------------
  3939. UnicodeString __fastcall AssemblyProperty(
  3940. TAssemblyLanguage Language, const UnicodeString & ClassName,
  3941. const UnicodeString & Name, int Value, bool Inline)
  3942. {
  3943. return AssemblyPropertyRaw(Language, ClassName, Name, IntToStr(Value), Inline);
  3944. }
  3945. //---------------------------------------------------------------------
  3946. UnicodeString __fastcall AssemblyBoolean(TAssemblyLanguage Language, bool Value)
  3947. {
  3948. UnicodeString Result;
  3949. switch (Language)
  3950. {
  3951. case alCSharp:
  3952. Result = (Value ? L"true" : L"false");
  3953. break;
  3954. case alVBNET:
  3955. Result = (Value ? L"True" : L"False");
  3956. break;
  3957. case alPowerShell:
  3958. Result = (Value ? L"$True" : L"$False");
  3959. break;
  3960. }
  3961. return Result;
  3962. }
  3963. //---------------------------------------------------------------------
  3964. UnicodeString __fastcall AssemblyProperty(
  3965. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name, bool Value, bool Inline)
  3966. {
  3967. UnicodeString PropertyValue = AssemblyBoolean(Language, Value);
  3968. return AssemblyPropertyRaw(Language, ClassName, Name, PropertyValue, Inline);
  3969. }
  3970. //---------------------------------------------------------------------
  3971. UnicodeString __fastcall AssemblyNewClassInstance(TAssemblyLanguage Language, const UnicodeString & ClassName, bool Inline)
  3972. {
  3973. UnicodeString VariableName = AssemblyVariableName(Language, ClassName);
  3974. UnicodeString RtfClass = RtfLibraryClass(ClassName);
  3975. UnicodeString Result;
  3976. switch (Language)
  3977. {
  3978. case alCSharp:
  3979. if (!Inline)
  3980. {
  3981. Result += RtfClass + RtfText(L" " + VariableName + L" = ");
  3982. }
  3983. Result += RtfKeyword(L"new") + RtfText(L" ") + RtfClass;
  3984. break;
  3985. case alVBNET:
  3986. if (!Inline)
  3987. {
  3988. Result += RtfText(VariableName + L" ") + RtfKeyword(L"As") + RtfText(L" ");
  3989. }
  3990. Result += RtfKeyword(L"New") + RtfText(" ") + RtfClass;
  3991. break;
  3992. case alPowerShell:
  3993. if (!Inline)
  3994. {
  3995. Result += RtfText(VariableName + L" = ");
  3996. }
  3997. Result += RtfKeyword(L"New-Object") + RtfText(L" " + AssemblyNamespace + L".") + RtfClass;
  3998. break;
  3999. }
  4000. return Result;
  4001. }
  4002. //---------------------------------------------------------------------
  4003. UnicodeString __fastcall AssemblyVariableDeclaration(TAssemblyLanguage Language)
  4004. {
  4005. UnicodeString Result;
  4006. switch (Language)
  4007. {
  4008. case alVBNET:
  4009. Result = RtfKeyword(L"Dim") + RtfText(L" ");
  4010. break;
  4011. }
  4012. return Result;
  4013. }
  4014. //---------------------------------------------------------------------
  4015. UnicodeString __fastcall AssemblyNewClassInstanceStart(
  4016. TAssemblyLanguage Language, const UnicodeString & ClassName, bool Inline)
  4017. {
  4018. UnicodeString SpaceOrPara = (Inline ? UnicodeString(L" ") : RtfPara);
  4019. UnicodeString Result;
  4020. if (!Inline)
  4021. {
  4022. Result += AssemblyVariableDeclaration(Language);
  4023. }
  4024. Result += AssemblyNewClassInstance(Language, ClassName, Inline);
  4025. switch (Language)
  4026. {
  4027. case alCSharp:
  4028. Result += SpaceOrPara + RtfText(L"{") + SpaceOrPara;
  4029. break;
  4030. case alVBNET:
  4031. // Historically we use Dim .. With instead of object initilizer.
  4032. // But for inline use, we have to use object initialize.
  4033. // We should consistently always use object initilizers.
  4034. // Unfortunately VB.NET object initializer (contrary to C#) does not allow trailing comma.
  4035. Result += SpaceOrPara + RtfKeyword(L"With");
  4036. if (Inline)
  4037. {
  4038. Result += RtfText(L" { ");
  4039. }
  4040. else
  4041. {
  4042. Result += RtfText(L" " + AssemblyVariableName(Language, ClassName)) + RtfPara;
  4043. }
  4044. break;
  4045. case alPowerShell:
  4046. Result += RtfText(" -Property @{") + SpaceOrPara;
  4047. break;
  4048. }
  4049. return Result;
  4050. }
  4051. //---------------------------------------------------------------------
  4052. UnicodeString __fastcall AssemblyNewClassInstanceEnd(TAssemblyLanguage Language, bool Inline)
  4053. {
  4054. UnicodeString InlineEnd = RtfText(L"}");
  4055. UnicodeString Result;
  4056. switch (Language)
  4057. {
  4058. case alCSharp:
  4059. if (Inline)
  4060. {
  4061. Result = InlineEnd;
  4062. }
  4063. else
  4064. {
  4065. Result = RtfText(L"};") + RtfPara;
  4066. }
  4067. break;
  4068. case alVBNET:
  4069. if (Inline)
  4070. {
  4071. Result = InlineEnd;
  4072. }
  4073. else
  4074. {
  4075. Result = RtfKeyword(L"End With") + RtfPara;
  4076. }
  4077. break;
  4078. case alPowerShell:
  4079. if (Inline)
  4080. {
  4081. Result = InlineEnd;
  4082. }
  4083. else
  4084. {
  4085. Result = RtfText(L"}") + RtfPara;
  4086. }
  4087. break;
  4088. }
  4089. return Result;
  4090. }
  4091. //---------------------------------------------------------------------------
  4092. UnicodeString __fastcall AssemblyAddRawSettings(
  4093. TAssemblyLanguage Language, TStrings * RawSettings, const UnicodeString & ClassName,
  4094. const UnicodeString & MethodName)
  4095. {
  4096. UnicodeString Result;
  4097. for (int Index = 0; Index < RawSettings->Count; Index++)
  4098. {
  4099. UnicodeString Name = RawSettings->Names[Index];
  4100. UnicodeString Value = RawSettings->ValueFromIndex[Index];
  4101. UnicodeString AddRawSettingsMethod =
  4102. RtfLibraryMethod(ClassName, MethodName, false) +
  4103. FORMAT(L"(%s, %s)", (AssemblyString(Language, Name), AssemblyString(Language, Value)));
  4104. UnicodeString VariableName = AssemblyVariableName(Language, ClassName);
  4105. Result += RtfText(VariableName + L".") + AddRawSettingsMethod + AssemblyStatementSeparator(Language) + RtfPara;
  4106. }
  4107. return Result;
  4108. }
  4109. //---------------------------------------------------------------------------
  4110. void __fastcall LoadScriptFromFile(UnicodeString FileName, TStrings * Lines, bool FallbackToAnsi)
  4111. {
  4112. std::unique_ptr<TFileStream> Stream(new TFileStream(ApiPath(FileName), fmOpenRead | fmShareDenyWrite));
  4113. // Simple stream reading, to make it work with named pipes too, not only with physical files
  4114. TBytes Buffer;
  4115. Buffer.Length = 10*1024;
  4116. int Read;
  4117. int Offset = 0;
  4118. do
  4119. {
  4120. Read = Stream->Read(Buffer, Offset, Buffer.Length - Offset);
  4121. Offset += Read;
  4122. if (Offset > Buffer.Length / 2)
  4123. {
  4124. Buffer.Length = Buffer.Length * 2;
  4125. }
  4126. }
  4127. while (Read > 0);
  4128. Buffer.Length = Offset;
  4129. TEncoding * Encoding = NULL;
  4130. int PreambleSize = TEncoding::GetBufferEncoding(Buffer, Encoding, TEncoding::UTF8);
  4131. UnicodeString S;
  4132. try
  4133. {
  4134. S = Encoding->GetString(Buffer, PreambleSize, Buffer.Length - PreambleSize);
  4135. }
  4136. catch (EEncodingError & E)
  4137. {
  4138. if (FallbackToAnsi)
  4139. {
  4140. S = TEncoding::ANSI->GetString(Buffer);
  4141. }
  4142. else
  4143. {
  4144. throw ExtException(LoadStr(TEXT_FILE_ENCODING), &E);
  4145. }
  4146. }
  4147. Lines->Text = S;
  4148. }
  4149. //---------------------------------------------------------------------------
  4150. UnicodeString __fastcall StripEllipsis(const UnicodeString & S)
  4151. {
  4152. UnicodeString Result = S;
  4153. if (Result.SubString(Result.Length() - Ellipsis.Length() + 1, Ellipsis.Length()) == Ellipsis)
  4154. {
  4155. Result.SetLength(Result.Length() - Ellipsis.Length());
  4156. Result = Result.TrimRight();
  4157. }
  4158. return Result;
  4159. }
  4160. //---------------------------------------------------------------------------
  4161. UnicodeString __fastcall GetFileMimeType(const UnicodeString & FileName)
  4162. {
  4163. wchar_t * MimeOut = NULL;
  4164. UnicodeString Result;
  4165. if (FindMimeFromData(NULL, FileName.c_str(), NULL, 0, NULL, FMFD_URLASFILENAME, &MimeOut, 0) == S_OK)
  4166. {
  4167. Result = MimeOut;
  4168. CoTaskMemFree(MimeOut);
  4169. }
  4170. return Result;
  4171. }
  4172. //---------------------------------------------------------------------------
  4173. TStrings * TlsCipherList()
  4174. {
  4175. std::unique_ptr<TStrings> Result(new TStringList());
  4176. // Exact method that neon uses. FTP uses TLS_method() (FTP needs server method too). But they have the same ciphers.
  4177. const SSL_METHOD * Method = TLS_client_method();
  4178. SSL_CTX * Ctx = SSL_CTX_new(Method);
  4179. SSL * Ssl = SSL_new(Ctx);
  4180. int Index = 0;
  4181. const char * CipherName;
  4182. do
  4183. {
  4184. CipherName = SSL_get_cipher_list(Ssl, Index);
  4185. Index++;
  4186. if (CipherName != NULL)
  4187. {
  4188. Result->Add(UnicodeString(CipherName));
  4189. }
  4190. }
  4191. while (CipherName != NULL);
  4192. return Result.release();
  4193. }
  4194. //---------------------------------------------------------------------------
  4195. void SetStringValueEvenIfEmpty(TStrings * Strings, const UnicodeString & Name, const UnicodeString & Value)
  4196. {
  4197. if (Value.IsEmpty())
  4198. {
  4199. int Index = Strings->IndexOfName(Name);
  4200. if (Index < 0)
  4201. {
  4202. Index = Strings->Add(L"");
  4203. }
  4204. UnicodeString Line = Name + Strings->NameValueSeparator;
  4205. Strings->Strings[Index] = Line;
  4206. }
  4207. else
  4208. {
  4209. Strings->Values[Name] = Value;
  4210. }
  4211. }
  4212. //---------------------------------------------------------------------------
  4213. DWORD __fastcall GetParentProcessId(HANDLE Snapshot, DWORD ProcessId)
  4214. {
  4215. DWORD Result = 0;
  4216. PROCESSENTRY32 ProcessEntry;
  4217. memset(&ProcessEntry, sizeof(ProcessEntry), 0);
  4218. ProcessEntry.dwSize = sizeof(PROCESSENTRY32);
  4219. if (Process32First(Snapshot, &ProcessEntry))
  4220. {
  4221. do
  4222. {
  4223. if (ProcessEntry.th32ProcessID == ProcessId)
  4224. {
  4225. Result = ProcessEntry.th32ParentProcessID;
  4226. }
  4227. } while (Process32Next(Snapshot, &ProcessEntry));
  4228. }
  4229. return Result;
  4230. }
  4231. //---------------------------------------------------------------------------
  4232. static UnicodeString GetProcessName(DWORD ProcessId)
  4233. {
  4234. UnicodeString Result;
  4235. HANDLE Process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessId);
  4236. // is common, when the parent process is installer, so we ignore it
  4237. if (Process)
  4238. {
  4239. Result.SetLength(MAX_PATH);
  4240. DWORD Len = GetModuleFileNameEx(Process, NULL, Result.c_str(), Result.Length());
  4241. Result.SetLength(Len);
  4242. // is common too, for some reason
  4243. if (!Result.IsEmpty())
  4244. {
  4245. Result = ExtractProgramName(FormatCommand(Result, UnicodeString()));
  4246. }
  4247. CloseHandle(Process);
  4248. }
  4249. return Result;
  4250. }
  4251. //---------------------------------------------------------------------------
  4252. UnicodeString ParentProcessName;
  4253. //---------------------------------------------------------------------------
  4254. UnicodeString __fastcall GetAncestorProcessName(int Levels)
  4255. {
  4256. UnicodeString Result;
  4257. bool Parent = (Levels == 1);
  4258. if (Parent && !ParentProcessName.IsEmpty())
  4259. {
  4260. Result = ParentProcessName;
  4261. }
  4262. else
  4263. {
  4264. try
  4265. {
  4266. HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  4267. DWORD ProcessId = GetCurrentProcessId();
  4268. typedef std::vector<DWORD> TProcesses;
  4269. TProcesses Processes;
  4270. // Either more to go (>0) or collecting all levels (-1 from GetAncestorProcessNames)
  4271. while ((Levels != 0) &&
  4272. (Levels > -20) && // prevent infinite loops
  4273. (ProcessId != 0))
  4274. {
  4275. const UnicodeString Sep(L", ");
  4276. ProcessId = GetParentProcessId(Snapshot, ProcessId);
  4277. // When ancestor process is terminated and another process reuses its ID, we may get a cycle.
  4278. TProcesses::const_iterator I = std::find(Processes.begin(), Processes.end(), ProcessId);
  4279. if (I != Processes.end())
  4280. {
  4281. int Index = I - Processes.begin();
  4282. AddToList(Result, FORMAT(L"cycle-%d", (Index)), Sep);
  4283. ProcessId = 0;
  4284. }
  4285. else
  4286. {
  4287. Processes.push_back(ProcessId);
  4288. if ((Levels < 0) && (ProcessId != 0))
  4289. {
  4290. UnicodeString Name = GetProcessName(ProcessId);
  4291. if (Name.IsEmpty())
  4292. {
  4293. Name = L"...";
  4294. ProcessId = 0;
  4295. }
  4296. AddToList(Result, Name, Sep);
  4297. }
  4298. Levels--;
  4299. }
  4300. }
  4301. if (Levels >= 0)
  4302. {
  4303. if (ProcessId == 0)
  4304. {
  4305. Result = L"err-notfound";
  4306. }
  4307. else
  4308. {
  4309. Result = GetProcessName(ProcessId);
  4310. }
  4311. }
  4312. else if (Result.IsEmpty())
  4313. {
  4314. Result = L"n/a";
  4315. }
  4316. CloseHandle(Snapshot);
  4317. }
  4318. catch (...)
  4319. {
  4320. Result = L"err-except";
  4321. }
  4322. if (Parent)
  4323. {
  4324. ParentProcessName = Result;
  4325. }
  4326. }
  4327. return Result;
  4328. }
  4329. //---------------------------------------------------------------------------
  4330. UnicodeString AncestorProcessNames;
  4331. //---------------------------------------------------------------------------
  4332. UnicodeString GetAncestorProcessNames()
  4333. {
  4334. if (AncestorProcessNames.IsEmpty())
  4335. {
  4336. AncestorProcessNames = GetAncestorProcessName(-1);
  4337. }
  4338. return AncestorProcessNames;
  4339. }
  4340. //---------------------------------------------------------------------------
  4341. void NotImplemented()
  4342. {
  4343. DebugFail();
  4344. throw Exception(L"Not implemented");
  4345. }
  4346. //---------------------------------------------------------------------------
  4347. void NotSupported()
  4348. {
  4349. throw Exception(MainInstructions(LoadStr(NOTSUPPORTED)));
  4350. }
  4351. //---------------------------------------------------------------------------
  4352. UnicodeString GetDividerLine()
  4353. {
  4354. return UnicodeString::StringOfChar(L'-', 27);
  4355. }
  4356. //---------------------------------------------------------------------------
  4357. static UnicodeString CutFeature(UnicodeString & Buf)
  4358. {
  4359. UnicodeString Result;
  4360. if (Buf.SubString(1, 1) == L"\"")
  4361. {
  4362. Buf.Delete(1, 1);
  4363. int P = Buf.Pos(L"\",");
  4364. if (P == 0)
  4365. {
  4366. Result = Buf;
  4367. Buf = UnicodeString();
  4368. // there should be the ending quote, but if not, just do nothing
  4369. if (Result.SubString(Result.Length(), 1) == L"\"")
  4370. {
  4371. Result.SetLength(Result.Length() - 1);
  4372. }
  4373. }
  4374. else
  4375. {
  4376. Result = Buf.SubString(1, P - 1);
  4377. Buf.Delete(1, P + 1);
  4378. }
  4379. Buf = Buf.TrimLeft();
  4380. }
  4381. else
  4382. {
  4383. Result = CutToChar(Buf, L',', true);
  4384. }
  4385. return Result;
  4386. }
  4387. //---------------------------------------------------------------------------
  4388. TStrings * ProcessFeatures(TStrings * Features, const UnicodeString & AFeaturesOverride)
  4389. {
  4390. std::unique_ptr<TStrings> Result(new TStringList());
  4391. UnicodeString FeaturesOverride = AFeaturesOverride;
  4392. if (FeaturesOverride.SubString(1, 1) == L"*")
  4393. {
  4394. FeaturesOverride.Delete(1, 1);
  4395. while (!FeaturesOverride.IsEmpty())
  4396. {
  4397. UnicodeString Feature = CutFeature(FeaturesOverride);
  4398. Result->Add(Feature);
  4399. }
  4400. }
  4401. else
  4402. {
  4403. std::unique_ptr<TStrings> DeleteFeatures(CreateSortedStringList());
  4404. std::unique_ptr<TStrings> AddFeatures(new TStringList());
  4405. while (!FeaturesOverride.IsEmpty())
  4406. {
  4407. UnicodeString Feature = CutFeature(FeaturesOverride);
  4408. if (Feature.SubString(1, 1) == L"-")
  4409. {
  4410. Feature.Delete(1, 1);
  4411. DeleteFeatures->Add(Feature.LowerCase());
  4412. }
  4413. else
  4414. {
  4415. if (Feature.SubString(1, 1) == L"+")
  4416. {
  4417. Feature.Delete(1, 1);
  4418. }
  4419. AddFeatures->Add(Feature);
  4420. }
  4421. }
  4422. for (int Index = 0; Index < Features->Count; Index++)
  4423. {
  4424. UnicodeString Feature = Features->Strings[Index];
  4425. if (DeleteFeatures->IndexOf(Feature) < 0)
  4426. {
  4427. Result->Add(Feature);
  4428. }
  4429. }
  4430. Result->AddStrings(AddFeatures.get());
  4431. }
  4432. return Result.release();
  4433. }
  4434. //---------------------------------------------------------------------