Common.cpp 136 KB

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