Common.cpp 119 KB

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