Common.cpp 138 KB

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