Common.cpp 138 KB

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