Common.cpp 133 KB

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