Common.cpp 119 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998
  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 ContainsTextSemiCaseSensitive(const UnicodeString & Text, const UnicodeString & SubText)
  838. {
  839. bool Result;
  840. if (AnsiLowerCase(SubText) == SubText)
  841. {
  842. Result = ContainsText(Text, SubText);
  843. }
  844. else
  845. {
  846. Result = ContainsStr(Text, SubText);
  847. }
  848. return Result;
  849. }
  850. //---------------------------------------------------------------------------
  851. bool __fastcall IsReservedName(UnicodeString FileName)
  852. {
  853. int P = FileName.Pos(L".");
  854. int Len = (P > 0) ? P - 1 : FileName.Length();
  855. if ((Len == 3) || (Len == 4))
  856. {
  857. if (P > 0)
  858. {
  859. FileName.SetLength(P - 1);
  860. }
  861. static UnicodeString Reserved[] = {
  862. L"CON", L"PRN", L"AUX", L"NUL",
  863. L"COM1", L"COM2", L"COM3", L"COM4", L"COM5", L"COM6", L"COM7", L"COM8", L"COM9",
  864. L"LPT1", L"LPT2", L"LPT3", L"LPT4", L"LPT5", L"LPT6", L"LPT7", L"LPT8", L"LPT9" };
  865. for (unsigned int Index = 0; Index < LENOF(Reserved); Index++)
  866. {
  867. if (SameText(FileName, Reserved[Index]))
  868. {
  869. return true;
  870. }
  871. }
  872. }
  873. return false;
  874. }
  875. //---------------------------------------------------------------------------
  876. // ApiPath support functions
  877. // Inspired by
  878. // https://stackoverflow.com/q/18580945/850848
  879. // This can be reimplemented using PathCchCanonicalizeEx on Windows 8 and later
  880. enum PATH_PREFIX_TYPE
  881. {
  882. PPT_UNKNOWN,
  883. PPT_ABSOLUTE, //Found absolute path that is none of the other types
  884. PPT_UNC, //Found \\server\share\ prefix
  885. PPT_LONG_UNICODE, //Found \\?\ prefix
  886. PPT_LONG_UNICODE_UNC, //Found \\?\UNC\ prefix
  887. };
  888. //---------------------------------------------------------------------------
  889. static int __fastcall PathRootLength(UnicodeString Path)
  890. {
  891. // Correction for PathSkipRoot API
  892. // Replace all /'s with \'s because PathSkipRoot can't handle /'s
  893. UnicodeString Result = ReplaceChar(Path, L'/', L'\\');
  894. // Now call the API
  895. LPCTSTR Buffer = PathSkipRoot(Result.c_str());
  896. return (Buffer != NULL) ? (Buffer - Result.c_str()) : -1;
  897. }
  898. //---------------------------------------------------------------------------
  899. static bool __fastcall PathIsRelative_CorrectedForMicrosoftStupidity(UnicodeString Path)
  900. {
  901. // Correction for PathIsRelative API
  902. // Replace all /'s with \'s because PathIsRelative can't handle /'s
  903. UnicodeString Result = ReplaceChar(Path, L'/', L'\\');
  904. //Now call the API
  905. return PathIsRelative(Result.c_str());
  906. }
  907. //---------------------------------------------------------------------------
  908. static int __fastcall GetOffsetAfterPathRoot(UnicodeString Path, PATH_PREFIX_TYPE & PrefixType)
  909. {
  910. // Checks if 'pPath' begins with the drive, share, prefix, etc
  911. // EXAMPLES:
  912. // Path Return: Points at: PrefixType:
  913. // Relative\Folder\File.txt 0 Relative\Folder\File.txt PPT_UNKNOWN
  914. // \RelativeToRoot\Folder 1 RelativeToRoot\Folder PPT_ABSOLUTE
  915. // C:\Windows\Folder 3 Windows\Folder PPT_ABSOLUTE
  916. // \\server\share\Desktop 15 Desktop PPT_UNC
  917. // \\?\C:\Windows\Folder 7 Windows\Folder PPT_LONG_UNICODE
  918. // \\?\UNC\server\share\Desktop 21 Desktop PPT_LONG_UNICODE_UNC
  919. // RETURN:
  920. // = Index in 'pPath' after the root, or
  921. // = 0 if no root was found
  922. int Result = 0;
  923. PrefixType = PPT_UNKNOWN;
  924. if (!Path.IsEmpty())
  925. {
  926. int Len = Path.Length();
  927. bool WinXPOnly = !IsWinVista();
  928. // The PathSkipRoot() API doesn't work correctly on Windows XP
  929. if (!WinXPOnly)
  930. {
  931. // Works since Vista and up, but still needs correction :)
  932. int RootLength = PathRootLength(Path);
  933. if (RootLength >= 0)
  934. {
  935. Result = RootLength + 1;
  936. }
  937. }
  938. // Now determine the type of prefix
  939. int IndCheckUNC = -1;
  940. if ((Len >= 8) &&
  941. (Path[1] == L'\\' || Path[1] == L'/') &&
  942. (Path[2] == L'\\' || Path[2] == L'/') &&
  943. (Path[3] == L'?') &&
  944. (Path[4] == L'\\' || Path[4] == L'/') &&
  945. (Path[5] == L'U' || Path[5] == L'u') &&
  946. (Path[6] == L'N' || Path[6] == L'n') &&
  947. (Path[7] == L'C' || Path[7] == L'c') &&
  948. (Path[8] == L'\\' || Path[8] == L'/'))
  949. {
  950. // Found \\?\UNC\ prefix
  951. PrefixType = PPT_LONG_UNICODE_UNC;
  952. if (WinXPOnly)
  953. {
  954. //For older OS
  955. Result += 8;
  956. }
  957. //Check for UNC share later
  958. IndCheckUNC = 8;
  959. }
  960. else if ((Len >= 4) &&
  961. (Path[1] == L'\\' || Path[1] == L'/') &&
  962. (Path[2] == L'\\' || Path[2] == L'/') &&
  963. (Path[3] == L'?') &&
  964. (Path[4] == L'\\' || Path[4] == L'/'))
  965. {
  966. // Found \\?\ prefix
  967. PrefixType = PPT_LONG_UNICODE;
  968. if (WinXPOnly)
  969. {
  970. //For older OS
  971. Result += 4;
  972. }
  973. }
  974. else if ((Len >= 2) &&
  975. (Path[1] == L'\\' || Path[1] == L'/') &&
  976. (Path[2] == L'\\' || Path[2] == L'/'))
  977. {
  978. // Check for UNC share later
  979. IndCheckUNC = 2;
  980. }
  981. if (IndCheckUNC >= 0)
  982. {
  983. // Check for UNC, i.e. \\server\share\ part
  984. int Index = IndCheckUNC;
  985. for (int SkipSlashes = 2; SkipSlashes > 0; SkipSlashes--)
  986. {
  987. for(; Index <= Len; Index++)
  988. {
  989. TCHAR z = Path[Index];
  990. if ((z == L'\\') || (z == L'/') || (Index >= Len))
  991. {
  992. Index++;
  993. if (SkipSlashes == 1)
  994. {
  995. if (PrefixType == PPT_UNKNOWN)
  996. {
  997. PrefixType = PPT_UNC;
  998. }
  999. if (WinXPOnly)
  1000. {
  1001. //For older OS
  1002. Result = Index;
  1003. }
  1004. }
  1005. break;
  1006. }
  1007. }
  1008. }
  1009. }
  1010. if (WinXPOnly)
  1011. {
  1012. // Only if we didn't determine any other type
  1013. if (PrefixType == PPT_UNKNOWN)
  1014. {
  1015. if (!PathIsRelative_CorrectedForMicrosoftStupidity(Path.SubString(Result, Path.Length() - Result + 1)))
  1016. {
  1017. PrefixType = PPT_ABSOLUTE;
  1018. }
  1019. }
  1020. // For older OS only
  1021. int RootLength = PathRootLength(Path.SubString(Result, Path.Length() - Result + 1));
  1022. if (RootLength >= 0)
  1023. {
  1024. Result = RootLength + 1;
  1025. }
  1026. }
  1027. else
  1028. {
  1029. // Only if we didn't determine any other type
  1030. if (PrefixType == PPT_UNKNOWN)
  1031. {
  1032. if (!PathIsRelative_CorrectedForMicrosoftStupidity(Path))
  1033. {
  1034. PrefixType = PPT_ABSOLUTE;
  1035. }
  1036. }
  1037. }
  1038. }
  1039. return Result;
  1040. }
  1041. //---------------------------------------------------------------------------
  1042. UnicodeString __fastcall MakeUnicodeLargePath(UnicodeString Path)
  1043. {
  1044. // Convert path from 'into a larger Unicode path, that allows up to 32,767 character length
  1045. UnicodeString Result;
  1046. if (!Path.IsEmpty())
  1047. {
  1048. // Determine the type of the existing prefix
  1049. PATH_PREFIX_TYPE PrefixType;
  1050. GetOffsetAfterPathRoot(Path, PrefixType);
  1051. // Assume path to be without change
  1052. Result = Path;
  1053. switch (PrefixType)
  1054. {
  1055. case PPT_ABSOLUTE:
  1056. {
  1057. // First we need to check if its an absolute path relative to the root
  1058. bool AddPrefix = true;
  1059. if ((Path.Length() >= 1) &&
  1060. ((Path[1] == L'\\') || (Path[1] == L'/')))
  1061. {
  1062. AddPrefix = FALSE;
  1063. // Get current root path
  1064. UnicodeString CurrentDir = GetCurrentDir();
  1065. PATH_PREFIX_TYPE PrefixType2; // unused
  1066. int Following = GetOffsetAfterPathRoot(CurrentDir, PrefixType2);
  1067. if (Following > 0)
  1068. {
  1069. AddPrefix = true;
  1070. Result = CurrentDir.SubString(1, Following - 1) + Result.SubString(2, Result.Length() - 1);
  1071. }
  1072. }
  1073. if (AddPrefix)
  1074. {
  1075. // Add \\?\ prefix
  1076. Result = L"\\\\?\\" + Result;
  1077. }
  1078. }
  1079. break;
  1080. case PPT_UNC:
  1081. // First we need to remove the opening slashes for UNC share
  1082. if ((Result.Length() >= 2) &&
  1083. ((Result[1] == L'\\') || (Result[1] == L'/')) &&
  1084. ((Result[2] == L'\\') || (Result[2] == L'/')))
  1085. {
  1086. Result = Result.SubString(3, Result.Length() - 2);
  1087. }
  1088. // Add \\?\UNC\ prefix
  1089. Result = L"\\\\?\\UNC\\" + Result;
  1090. break;
  1091. case PPT_LONG_UNICODE:
  1092. case PPT_LONG_UNICODE_UNC:
  1093. // nothing to do
  1094. break;
  1095. }
  1096. }
  1097. return Result;
  1098. }
  1099. //---------------------------------------------------------------------------
  1100. UnicodeString __fastcall ApiPath(UnicodeString Path)
  1101. {
  1102. UnicodeString Drive = ExtractFileDrive(Path);
  1103. // This may match even a path like "C:" or "\\server\\share", but we do not really care
  1104. if (Drive.IsEmpty() || (Path.SubString(Drive.Length() + 1, 1) != L"\\"))
  1105. {
  1106. Path = ExpandFileName(Path);
  1107. }
  1108. // Max path for directories is 12 characters shorter than max path for files
  1109. if (Path.Length() >= MAX_PATH - 12)
  1110. {
  1111. if (Configuration != NULL)
  1112. {
  1113. Configuration->Usage->Inc(L"LongPath");
  1114. }
  1115. Path = MakeUnicodeLargePath(Path);
  1116. }
  1117. return Path;
  1118. }
  1119. //---------------------------------------------------------------------------
  1120. UnicodeString __fastcall DisplayableStr(const RawByteString & Str)
  1121. {
  1122. bool Displayable = true;
  1123. int Index = 1;
  1124. while ((Index <= Str.Length()) && Displayable)
  1125. {
  1126. if (((Str[Index] < '\x20') || (static_cast<unsigned char>(Str[Index]) >= static_cast<unsigned char>('\x80'))) &&
  1127. (Str[Index] != '\n') && (Str[Index] != '\r') && (Str[Index] != '\t') && (Str[Index] != '\b'))
  1128. {
  1129. Displayable = false;
  1130. }
  1131. Index++;
  1132. }
  1133. UnicodeString Result;
  1134. if (Displayable)
  1135. {
  1136. Result = L"\"";
  1137. for (int Index = 1; Index <= Str.Length(); Index++)
  1138. {
  1139. switch (Str[Index])
  1140. {
  1141. case '\n':
  1142. Result += L"\\n";
  1143. break;
  1144. case '\r':
  1145. Result += L"\\r";
  1146. break;
  1147. case '\t':
  1148. Result += L"\\t";
  1149. break;
  1150. case '\b':
  1151. Result += L"\\b";
  1152. break;
  1153. case '\\':
  1154. Result += L"\\\\";
  1155. break;
  1156. case '"':
  1157. Result += L"\\\"";
  1158. break;
  1159. default:
  1160. Result += wchar_t(Str[Index]);
  1161. break;
  1162. }
  1163. }
  1164. Result += L"\"";
  1165. }
  1166. else
  1167. {
  1168. Result = L"0x" + BytesToHex(Str);
  1169. }
  1170. return Result;
  1171. }
  1172. //---------------------------------------------------------------------------
  1173. UnicodeString __fastcall ByteToHex(unsigned char B, bool UpperCase)
  1174. {
  1175. static wchar_t UpperDigits[] = L"0123456789ABCDEF";
  1176. static wchar_t LowerDigits[] = L"0123456789abcdef";
  1177. const wchar_t * Digits = (UpperCase ? UpperDigits : LowerDigits);
  1178. UnicodeString Result;
  1179. Result.SetLength(2);
  1180. Result[1] = Digits[(B & 0xF0) >> 4];
  1181. Result[2] = Digits[(B & 0x0F) >> 0];
  1182. return Result;
  1183. }
  1184. //---------------------------------------------------------------------------
  1185. UnicodeString __fastcall BytesToHex(const unsigned char * B, size_t Length, bool UpperCase, wchar_t Separator)
  1186. {
  1187. UnicodeString Result;
  1188. for (size_t i = 0; i < Length; i++)
  1189. {
  1190. Result += ByteToHex(B[i], UpperCase);
  1191. if ((Separator != L'\0') && (i < Length - 1))
  1192. {
  1193. Result += Separator;
  1194. }
  1195. }
  1196. return Result;
  1197. }
  1198. //---------------------------------------------------------------------------
  1199. UnicodeString __fastcall BytesToHex(RawByteString Str, bool UpperCase, wchar_t Separator)
  1200. {
  1201. return BytesToHex(reinterpret_cast<const unsigned char *>(Str.c_str()), Str.Length(), UpperCase, Separator);
  1202. }
  1203. //---------------------------------------------------------------------------
  1204. UnicodeString __fastcall CharToHex(wchar_t Ch, bool UpperCase)
  1205. {
  1206. return BytesToHex(reinterpret_cast<const unsigned char *>(&Ch), sizeof(Ch), UpperCase);
  1207. }
  1208. //---------------------------------------------------------------------------
  1209. RawByteString __fastcall HexToBytes(const UnicodeString Hex)
  1210. {
  1211. static UnicodeString Digits = L"0123456789ABCDEF";
  1212. RawByteString Result;
  1213. int L, P1, P2;
  1214. L = Hex.Length();
  1215. if (L % 2 == 0)
  1216. {
  1217. for (int i = 1; i <= Hex.Length(); i += 2)
  1218. {
  1219. P1 = Digits.Pos((wchar_t)toupper(Hex[i]));
  1220. P2 = Digits.Pos((wchar_t)toupper(Hex[i + 1]));
  1221. if (P1 <= 0 || P2 <= 0)
  1222. {
  1223. Result = L"";
  1224. break;
  1225. }
  1226. else
  1227. {
  1228. Result += static_cast<char>((P1 - 1) * 16 + P2 - 1);
  1229. }
  1230. }
  1231. }
  1232. return Result;
  1233. }
  1234. //---------------------------------------------------------------------------
  1235. unsigned char __fastcall HexToByte(const UnicodeString Hex)
  1236. {
  1237. static UnicodeString Digits = L"0123456789ABCDEF";
  1238. DebugAssert(Hex.Length() == 2);
  1239. int P1 = Digits.Pos((wchar_t)toupper(Hex[1]));
  1240. int P2 = Digits.Pos((wchar_t)toupper(Hex[2]));
  1241. return
  1242. static_cast<unsigned char>(((P1 <= 0) || (P2 <= 0)) ? 0 : (((P1 - 1) << 4) + (P2 - 1)));
  1243. }
  1244. //---------------------------------------------------------------------------
  1245. bool __fastcall IsLowerCaseLetter(wchar_t Ch)
  1246. {
  1247. return (Ch >= 'a') && (Ch <= 'z');
  1248. }
  1249. //---------------------------------------------------------------------------
  1250. bool __fastcall IsUpperCaseLetter(wchar_t Ch)
  1251. {
  1252. return (Ch >= 'A') && (Ch <= 'Z');
  1253. }
  1254. //---------------------------------------------------------------------------
  1255. bool __fastcall IsLetter(wchar_t Ch)
  1256. {
  1257. return IsLowerCaseLetter(Ch) || IsUpperCaseLetter(Ch);
  1258. }
  1259. //---------------------------------------------------------------------------
  1260. bool __fastcall IsDigit(wchar_t Ch)
  1261. {
  1262. return (Ch >= '0') && (Ch <= '9');
  1263. }
  1264. //---------------------------------------------------------------------------
  1265. bool __fastcall IsHex(wchar_t Ch)
  1266. {
  1267. return
  1268. IsDigit(Ch) ||
  1269. ((Ch >= 'A') && (Ch <= 'F')) ||
  1270. ((Ch >= 'a') && (Ch <= 'f'));
  1271. }
  1272. //---------------------------------------------------------------------------
  1273. TSearchRecSmart::TSearchRecSmart()
  1274. {
  1275. FLastWriteTimeSource.dwLowDateTime = 0;
  1276. FLastWriteTimeSource.dwLowDateTime = 0;
  1277. }
  1278. //---------------------------------------------------------------------------
  1279. TDateTime TSearchRecSmart::GetLastWriteTime() const
  1280. {
  1281. if ((FindData.ftLastWriteTime.dwLowDateTime != FLastWriteTimeSource.dwLowDateTime) ||
  1282. (FindData.ftLastWriteTime.dwHighDateTime != FLastWriteTimeSource.dwHighDateTime))
  1283. {
  1284. FLastWriteTimeSource = FindData.ftLastWriteTime;
  1285. FLastWriteTime = FileTimeToDateTime(FLastWriteTimeSource);
  1286. }
  1287. return FLastWriteTime;
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. bool TSearchRecSmart::IsRealFile() const
  1291. {
  1292. return ::IsRealFile(Name);
  1293. }
  1294. //---------------------------------------------------------------------------
  1295. bool TSearchRecSmart::IsDirectory() const
  1296. {
  1297. return FLAGSET(Attr, faDirectory);
  1298. }
  1299. //---------------------------------------------------------------------------
  1300. bool TSearchRecSmart::IsHidden() const
  1301. {
  1302. return FLAGSET(Attr, faHidden);
  1303. }
  1304. //---------------------------------------------------------------------------
  1305. TSearchRecOwned::~TSearchRecOwned()
  1306. {
  1307. if (Opened)
  1308. {
  1309. FindClose(*this);
  1310. }
  1311. }
  1312. //---------------------------------------------------------------------------
  1313. void TSearchRecOwned::Close()
  1314. {
  1315. FindClose(*this);
  1316. Opened = false;
  1317. }
  1318. //---------------------------------------------------------------------------
  1319. int __fastcall FindCheck(int Result, const UnicodeString & Path)
  1320. {
  1321. if ((Result != ERROR_SUCCESS) &&
  1322. (Result != ERROR_FILE_NOT_FOUND) &&
  1323. (Result != ERROR_NO_MORE_FILES))
  1324. {
  1325. throw EOSExtException(FMTLOAD(FIND_FILE_ERROR, (Path)), Result);
  1326. }
  1327. return Result;
  1328. }
  1329. //---------------------------------------------------------------------------
  1330. int __fastcall FindFirstUnchecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1331. {
  1332. F.Path = Path;
  1333. int Result = FindFirst(ApiPath(Path), Attr, F);
  1334. F.Opened = (Result == 0);
  1335. return Result;
  1336. }
  1337. //---------------------------------------------------------------------------
  1338. int __fastcall FindFirstChecked(const UnicodeString & Path, int Attr, TSearchRecChecked & F)
  1339. {
  1340. int Result = FindFirstUnchecked(Path, Attr, F);
  1341. return FindCheck(Result, F.Path);
  1342. }
  1343. //---------------------------------------------------------------------------
  1344. // Equivalent to FindNext, just to complement to FindFirstUnchecked
  1345. int __fastcall FindNextUnchecked(TSearchRecChecked & F)
  1346. {
  1347. return FindNext(F);
  1348. }
  1349. //---------------------------------------------------------------------------
  1350. // It can make sense to use FindNextChecked, even if unchecked FindFirst is used.
  1351. // I.e. even if we do not care that FindFirst failed, if FindNext
  1352. // fails after successful FindFirst, it means some terrible problem
  1353. int __fastcall FindNextChecked(TSearchRecChecked & F)
  1354. {
  1355. return FindCheck(FindNextUnchecked(F), F.Path);
  1356. }
  1357. //---------------------------------------------------------------------------
  1358. bool __fastcall FileSearchRec(const UnicodeString FileName, TSearchRec & Rec)
  1359. {
  1360. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1361. bool Result = (FindFirst(ApiPath(FileName), FindAttrs, Rec) == 0);
  1362. if (Result)
  1363. {
  1364. FindClose(Rec);
  1365. }
  1366. return Result;
  1367. }
  1368. //---------------------------------------------------------------------------
  1369. void CopySearchRec(const TSearchRec & Source, TSearchRec & Dest)
  1370. {
  1371. // Strangely issues a compiler warning (W8111 due to TSearchRec::Time), when used in Script.cpp, but not here.
  1372. Dest = Source;
  1373. }
  1374. //---------------------------------------------------------------------------
  1375. bool __fastcall IsRealFile(const UnicodeString & FileName)
  1376. {
  1377. return (FileName != THISDIRECTORY) && (FileName != PARENTDIRECTORY);
  1378. }
  1379. //---------------------------------------------------------------------------
  1380. UnicodeString GetOSInfo()
  1381. {
  1382. UnicodeString Result = WindowsVersionLong();
  1383. AddToList(Result, WindowsProductName(), L" - ");
  1384. return Result;
  1385. }
  1386. //---------------------------------------------------------------------------
  1387. UnicodeString GetEnvironmentInfo()
  1388. {
  1389. UnicodeString Result = FORMAT(L"WinSCP %s (OS %s)", (Configuration->VersionStr, GetOSInfo()));
  1390. return Result;
  1391. }
  1392. //---------------------------------------------------------------------------
  1393. void __fastcall ProcessLocalDirectory(UnicodeString DirName,
  1394. TProcessLocalFileEvent CallBackFunc, void * Param,
  1395. int FindAttrs)
  1396. {
  1397. DebugAssert(CallBackFunc);
  1398. if (FindAttrs < 0)
  1399. {
  1400. FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1401. }
  1402. DirName = IncludeTrailingBackslash(DirName);
  1403. TSearchRecOwned SearchRec;
  1404. if (FindFirstChecked(DirName + L"*.*", FindAttrs, SearchRec) == 0)
  1405. {
  1406. do
  1407. {
  1408. if (SearchRec.IsRealFile())
  1409. {
  1410. CallBackFunc(DirName + SearchRec.Name, SearchRec, Param);
  1411. }
  1412. } while (FindNextChecked(SearchRec) == 0);
  1413. }
  1414. }
  1415. //---------------------------------------------------------------------------
  1416. int __fastcall FileGetAttrFix(const UnicodeString FileName)
  1417. {
  1418. // The default for FileGetAttr is to follow links
  1419. bool FollowLink = true;
  1420. // WORKAROUND:
  1421. // But the FileGetAttr when called for link with FollowLink set will always fail
  1422. // as it calls InternalGetFileNameFromSymLink, which test for CheckWin32Version(6, 0)
  1423. if (!IsWinVista())
  1424. {
  1425. FollowLink = false;
  1426. }
  1427. int Result = FileGetAttr(FileName, FollowLink);
  1428. if (Result < 0)
  1429. {
  1430. // When referring to files in some special symlinked locations
  1431. // (like a deduplicated drive or a commvault archive), the first call to GetFileAttributes fails.
  1432. Result = FileGetAttr(FileName, FollowLink);
  1433. }
  1434. return Result;
  1435. }
  1436. //---------------------------------------------------------------------------
  1437. TDateTime __fastcall EncodeDateVerbose(Word Year, Word Month, Word Day)
  1438. {
  1439. try
  1440. {
  1441. TDateTime DateTime = EncodeDate(Year, Month, Day);
  1442. return DateTime;
  1443. }
  1444. catch (EConvertError & E)
  1445. {
  1446. throw EConvertError(FORMAT(L"%s [%d-%d-%d]", (E.Message, int(Year), int(Month), int(Day))));
  1447. }
  1448. }
  1449. //---------------------------------------------------------------------------
  1450. TDateTime __fastcall EncodeTimeVerbose(Word Hour, Word Min, Word Sec, Word MSec)
  1451. {
  1452. try
  1453. {
  1454. TDateTime DateTime = EncodeTime(Hour, Min, Sec, MSec);
  1455. return DateTime;
  1456. }
  1457. catch (EConvertError & E)
  1458. {
  1459. throw EConvertError(FORMAT(L"%s [%d:%d:%d.%d]", (E.Message, int(Hour), int(Min), int(Sec), int(MSec))));
  1460. }
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. TDateTime __fastcall SystemTimeToDateTimeVerbose(const SYSTEMTIME & SystemTime)
  1464. {
  1465. try
  1466. {
  1467. TDateTime DateTime = SystemTimeToDateTime(SystemTime);
  1468. return DateTime;
  1469. }
  1470. catch (EConvertError & E)
  1471. {
  1472. 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))));
  1473. }
  1474. }
  1475. //---------------------------------------------------------------------------
  1476. struct TDateTimeParams
  1477. {
  1478. TDateTime UnixEpoch;
  1479. double BaseDifference;
  1480. long BaseDifferenceSec;
  1481. // All Current* are actually global, not per-year and
  1482. // are valid for Year 0 (current) only
  1483. double CurrentDaylightDifference;
  1484. long CurrentDaylightDifferenceSec;
  1485. double CurrentDifference;
  1486. long CurrentDifferenceSec;
  1487. double StandardDifference;
  1488. long StandardDifferenceSec;
  1489. double DaylightDifference;
  1490. long DaylightDifferenceSec;
  1491. SYSTEMTIME SystemStandardDate;
  1492. SYSTEMTIME SystemDaylightDate;
  1493. TDateTime StandardDate;
  1494. TDateTime DaylightDate;
  1495. UnicodeString StandardName;
  1496. UnicodeString DaylightName;
  1497. // This is actually global, not per-year
  1498. bool DaylightHack;
  1499. bool HasDST() const
  1500. {
  1501. // On some systems it occurs that StandardDate is unset, while
  1502. // DaylightDate is set. MSDN states that this is invalid and
  1503. // should be treated as if there is no daylight saving.
  1504. // So check both.
  1505. return
  1506. (SystemStandardDate.wMonth != 0) &&
  1507. (SystemDaylightDate.wMonth != 0);
  1508. }
  1509. bool SummerDST() const
  1510. {
  1511. return HasDST() && (DaylightDate < StandardDate);
  1512. }
  1513. };
  1514. typedef std::map<int, TDateTimeParams> TYearlyDateTimeParams;
  1515. static TYearlyDateTimeParams YearlyDateTimeParams;
  1516. static std::unique_ptr<TCriticalSection> DateTimeParamsSection(TraceInitPtr(new TCriticalSection()));
  1517. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1518. TDateTime & Result);
  1519. //---------------------------------------------------------------------------
  1520. static unsigned short __fastcall DecodeYear(const TDateTime & DateTime)
  1521. {
  1522. unsigned short Year, Month, Day;
  1523. DecodeDate(DateTime, Year, Month, Day);
  1524. return Year;
  1525. }
  1526. //---------------------------------------------------------------------------
  1527. static const TDateTimeParams * __fastcall GetDateTimeParams(unsigned short Year)
  1528. {
  1529. TGuard Guard(DateTimeParamsSection.get());
  1530. TDateTimeParams * Result;
  1531. TYearlyDateTimeParams::iterator i = YearlyDateTimeParams.find(Year);
  1532. if (i != YearlyDateTimeParams.end())
  1533. {
  1534. Result = &(*i).second;
  1535. }
  1536. else
  1537. {
  1538. // creates new entry as a side effect
  1539. Result = &YearlyDateTimeParams[Year];
  1540. TIME_ZONE_INFORMATION TZI;
  1541. unsigned long GTZI;
  1542. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  1543. typedef BOOL WINAPI (* TGetTimeZoneInformationForYear)(USHORT wYear, PDYNAMIC_TIME_ZONE_INFORMATION pdtzi, LPTIME_ZONE_INFORMATION ptzi);
  1544. TGetTimeZoneInformationForYear GetTimeZoneInformationForYear =
  1545. (TGetTimeZoneInformationForYear)GetProcAddress(Kernel32, "GetTimeZoneInformationForYear");
  1546. if ((Year == 0) || (GetTimeZoneInformationForYear == NULL))
  1547. {
  1548. GTZI = GetTimeZoneInformation(&TZI);
  1549. }
  1550. else
  1551. {
  1552. GetTimeZoneInformationForYear(Year, NULL, &TZI);
  1553. GTZI = TIME_ZONE_ID_UNKNOWN;
  1554. }
  1555. switch (GTZI)
  1556. {
  1557. case TIME_ZONE_ID_UNKNOWN:
  1558. Result->CurrentDaylightDifferenceSec = 0;
  1559. break;
  1560. case TIME_ZONE_ID_STANDARD:
  1561. Result->CurrentDaylightDifferenceSec = TZI.StandardBias;
  1562. break;
  1563. case TIME_ZONE_ID_DAYLIGHT:
  1564. Result->CurrentDaylightDifferenceSec = TZI.DaylightBias;
  1565. break;
  1566. case TIME_ZONE_ID_INVALID:
  1567. default:
  1568. throw Exception(TIMEZONE_ERROR);
  1569. }
  1570. Result->BaseDifferenceSec = TZI.Bias;
  1571. Result->BaseDifference = double(TZI.Bias) / MinsPerDay;
  1572. Result->BaseDifferenceSec *= SecsPerMin;
  1573. Result->CurrentDifferenceSec = TZI.Bias +
  1574. Result->CurrentDaylightDifferenceSec;
  1575. Result->CurrentDifference =
  1576. double(Result->CurrentDifferenceSec) / MinsPerDay;
  1577. Result->CurrentDifferenceSec *= SecsPerMin;
  1578. Result->CurrentDaylightDifference =
  1579. double(Result->CurrentDaylightDifferenceSec) / MinsPerDay;
  1580. Result->CurrentDaylightDifferenceSec *= SecsPerMin;
  1581. Result->DaylightDifferenceSec = TZI.DaylightBias * SecsPerMin;
  1582. Result->DaylightDifference = double(TZI.DaylightBias) / MinsPerDay;
  1583. Result->StandardDifferenceSec = TZI.StandardBias * SecsPerMin;
  1584. Result->StandardDifference = double(TZI.StandardBias) / MinsPerDay;
  1585. Result->SystemStandardDate = TZI.StandardDate;
  1586. Result->SystemDaylightDate = TZI.DaylightDate;
  1587. unsigned short AYear = (Year != 0) ? Year : DecodeYear(Now());
  1588. if (Result->HasDST())
  1589. {
  1590. EncodeDSTMargin(Result->SystemStandardDate, AYear, Result->StandardDate);
  1591. EncodeDSTMargin(Result->SystemDaylightDate, AYear, Result->DaylightDate);
  1592. }
  1593. Result->StandardName = TZI.StandardName;
  1594. Result->DaylightName = TZI.DaylightName;
  1595. Result->DaylightHack = !IsWin7();
  1596. }
  1597. return Result;
  1598. }
  1599. //---------------------------------------------------------------------------
  1600. static void __fastcall EncodeDSTMargin(const SYSTEMTIME & Date, unsigned short Year,
  1601. TDateTime & Result)
  1602. {
  1603. if (Date.wYear == 0)
  1604. {
  1605. TDateTime Temp = EncodeDateVerbose(Year, Date.wMonth, 1);
  1606. Result = Temp + ((Date.wDayOfWeek - DayOfWeek(Temp) + 8) % 7) +
  1607. (7 * (Date.wDay - 1));
  1608. // Day 5 means, the last occurence of day-of-week in month
  1609. if (Date.wDay == 5)
  1610. {
  1611. unsigned short Month = static_cast<unsigned short>(Date.wMonth + 1);
  1612. if (Month > 12)
  1613. {
  1614. Month = static_cast<unsigned short>(Month - 12);
  1615. Year++;
  1616. }
  1617. if (Result >= EncodeDateVerbose(Year, Month, 1))
  1618. {
  1619. Result -= 7;
  1620. }
  1621. }
  1622. Result += EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond,
  1623. Date.wMilliseconds);
  1624. }
  1625. else
  1626. {
  1627. Result = EncodeDateVerbose(Year, Date.wMonth, Date.wDay) +
  1628. EncodeTimeVerbose(Date.wHour, Date.wMinute, Date.wSecond, Date.wMilliseconds);
  1629. }
  1630. }
  1631. //---------------------------------------------------------------------------
  1632. static bool __fastcall IsDateInDST(const TDateTime & DateTime)
  1633. {
  1634. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1635. bool Result;
  1636. // On some systems it occurs that StandardDate is unset, while
  1637. // DaylightDate is set. MSDN states that this is invalid and
  1638. // should be treated as if there is no daylight saving.
  1639. // So check both.
  1640. if (!Params->HasDST())
  1641. {
  1642. Result = false;
  1643. }
  1644. else
  1645. {
  1646. if (Params->SummerDST())
  1647. {
  1648. Result =
  1649. (DateTime >= Params->DaylightDate) &&
  1650. (DateTime < Params->StandardDate);
  1651. }
  1652. else
  1653. {
  1654. Result =
  1655. (DateTime < Params->StandardDate) ||
  1656. (DateTime >= Params->DaylightDate);
  1657. }
  1658. }
  1659. return Result;
  1660. }
  1661. //---------------------------------------------------------------------------
  1662. bool __fastcall UsesDaylightHack()
  1663. {
  1664. return GetDateTimeParams(0)->DaylightHack;
  1665. }
  1666. //---------------------------------------------------------------------------
  1667. TDateTime __fastcall UnixToDateTime(__int64 TimeStamp, TDSTMode DSTMode)
  1668. {
  1669. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1670. TDateTime Result = UnixDateDelta + (double(TimeStamp) / SecsPerDay);
  1671. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(Result));
  1672. if (Params->DaylightHack)
  1673. {
  1674. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  1675. {
  1676. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1677. Result -= CurrentParams->CurrentDifference;
  1678. }
  1679. else if (DSTMode == dstmKeep)
  1680. {
  1681. Result -= Params->BaseDifference;
  1682. }
  1683. }
  1684. else
  1685. {
  1686. Result -= Params->BaseDifference;
  1687. }
  1688. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1689. {
  1690. Result -= DSTDifferenceForTime(Result);
  1691. }
  1692. return Result;
  1693. }
  1694. //---------------------------------------------------------------------------
  1695. __int64 __fastcall Round(double Number)
  1696. {
  1697. double Floor = floor(Number);
  1698. double Ceil = ceil(Number);
  1699. return static_cast<__int64>(((Number - Floor) > (Ceil - Number)) ? Ceil : Floor);
  1700. }
  1701. //---------------------------------------------------------------------------
  1702. bool __fastcall TryRelativeStrToDateTime(UnicodeString S, TDateTime & DateTime, bool Add)
  1703. {
  1704. S = S.Trim();
  1705. int Index = 1;
  1706. if (SameText(S, L"today"))
  1707. {
  1708. S = L"0DS";
  1709. }
  1710. else if (SameText(S, L"yesterday"))
  1711. {
  1712. S = L"1DS";
  1713. }
  1714. while ((Index <= S.Length()) && IsDigit(S[Index]))
  1715. {
  1716. Index++;
  1717. }
  1718. UnicodeString NumberStr = S.SubString(1, Index - 1);
  1719. int Number;
  1720. bool Result = TryStrToInt(NumberStr, Number);
  1721. if (Result)
  1722. {
  1723. if (!Add)
  1724. {
  1725. Number = -Number;
  1726. }
  1727. S.Delete(1, Index - 1);
  1728. S = S.Trim().UpperCase();
  1729. bool Start = (S.Length() == 2) && (S[2] == L'S');
  1730. if (Start)
  1731. {
  1732. S.SetLength(S.Length() - 1);
  1733. }
  1734. DateTime = Now();
  1735. // These may not overlap with ParseSize (K, M and G)
  1736. if (S == L"S")
  1737. {
  1738. DateTime = IncSecond(DateTime, Number);
  1739. if (Start)
  1740. {
  1741. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheSecond(DateTime)));
  1742. }
  1743. }
  1744. else if (S == L"N")
  1745. {
  1746. DateTime = IncMinute(DateTime, Number);
  1747. if (Start)
  1748. {
  1749. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheMinute(DateTime)));
  1750. }
  1751. }
  1752. else if (S == L"H")
  1753. {
  1754. DateTime = IncHour(DateTime, Number);
  1755. if (Start)
  1756. {
  1757. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheHour(DateTime)));
  1758. }
  1759. }
  1760. else if (S == L"D")
  1761. {
  1762. DateTime = IncDay(DateTime, Number);
  1763. if (Start)
  1764. {
  1765. DateTime = IncMilliSecond(DateTime, -static_cast<int>(MilliSecondOfTheDay(DateTime)));
  1766. }
  1767. }
  1768. else if (S == L"Y")
  1769. {
  1770. DateTime = IncYear(DateTime, Number);
  1771. if (Start)
  1772. {
  1773. DateTime = IncMilliSecond(DateTime, -MilliSecondOfTheYear(DateTime));
  1774. }
  1775. }
  1776. else
  1777. {
  1778. Result = false;
  1779. }
  1780. }
  1781. return Result;
  1782. }
  1783. //---------------------------------------------------------------------------
  1784. bool TryStrToDateTimeStandard(const UnicodeString & S, TDateTime & Value)
  1785. {
  1786. TFormatSettings FormatSettings = TFormatSettings::Create(GetDefaultLCID());
  1787. FormatSettings.DateSeparator = L'-';
  1788. FormatSettings.TimeSeparator = L':';
  1789. FormatSettings.ShortDateFormat = "yyyy/mm/dd";
  1790. FormatSettings.ShortTimeFormat = "hh:nn:ss";
  1791. return TryStrToDateTime(S, Value, FormatSettings);
  1792. }
  1793. //---------------------------------------------------------------------------
  1794. const wchar_t KiloSize = L'K';
  1795. const wchar_t MegaSize = L'M';
  1796. const wchar_t GigaSize = L'G';
  1797. //---------------------------------------------------------------------------
  1798. // Keep consistent with parse_blocksize
  1799. bool __fastcall TryStrToSize(UnicodeString SizeStr, __int64 & Size)
  1800. {
  1801. int Index = 0;
  1802. while ((Index + 1 <= SizeStr.Length()) && IsDigit(SizeStr[Index + 1]))
  1803. {
  1804. Index++;
  1805. }
  1806. bool Result =
  1807. (Index > 0) && TryStrToInt64(SizeStr.SubString(1, Index), Size);
  1808. if (Result)
  1809. {
  1810. SizeStr = SizeStr.SubString(Index + 1, SizeStr.Length() - Index).Trim();
  1811. if (!SizeStr.IsEmpty())
  1812. {
  1813. Result = (SizeStr.Length() == 1);
  1814. if (Result)
  1815. {
  1816. wchar_t Unit = (wchar_t)toupper(SizeStr[1]);
  1817. switch (Unit)
  1818. {
  1819. case GigaSize:
  1820. Size *= 1024;
  1821. // fallthru
  1822. case MegaSize:
  1823. Size *= 1024;
  1824. // fallthru
  1825. case KiloSize:
  1826. Size *= 1024;
  1827. break;
  1828. default:
  1829. Result = false;
  1830. }
  1831. }
  1832. }
  1833. }
  1834. return Result;
  1835. }
  1836. //---------------------------------------------------------------------------
  1837. UnicodeString __fastcall SizeToStr(__int64 Size)
  1838. {
  1839. UnicodeString Result;
  1840. if ((Size <= 0) || ((Size % 1024) != 0))
  1841. {
  1842. Result = IntToStr(Size);
  1843. }
  1844. else
  1845. {
  1846. Size /= 1024;
  1847. if ((Size % 1024) != 0)
  1848. {
  1849. Result = IntToStr(Size) + KiloSize;
  1850. }
  1851. else
  1852. {
  1853. Size /= 1024;
  1854. if ((Size % 1024) != 0)
  1855. {
  1856. Result = IntToStr(Size) + MegaSize;
  1857. }
  1858. else
  1859. {
  1860. Size /= 1024;
  1861. Result = IntToStr(Size) + GigaSize;
  1862. }
  1863. }
  1864. }
  1865. return Result;
  1866. }
  1867. //---------------------------------------------------------------------------
  1868. static __int64 __fastcall DateTimeToUnix(const TDateTime DateTime)
  1869. {
  1870. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1871. DebugAssert(int(EncodeDateVerbose(1970, 1, 1)) == UnixDateDelta);
  1872. return Round(double(DateTime - UnixDateDelta) * SecsPerDay) +
  1873. CurrentParams->CurrentDifferenceSec;
  1874. }
  1875. //---------------------------------------------------------------------------
  1876. FILETIME __fastcall DateTimeToFileTime(const TDateTime DateTime,
  1877. TDSTMode /*DSTMode*/)
  1878. {
  1879. __int64 UnixTimeStamp = ::DateTimeToUnix(DateTime);
  1880. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1881. if (!Params->DaylightHack)
  1882. {
  1883. // We should probably use reversed code of FileTimeToDateTime here instead of custom implementation
  1884. // We are incrementing and decrementing BaseDifferenceSec because it
  1885. // can actually change between years
  1886. // (as it did in Belarus from GMT+2 to GMT+3 between 2011 and 2012)
  1887. UnixTimeStamp += (IsDateInDST(DateTime) ?
  1888. Params->DaylightDifferenceSec : Params->StandardDifferenceSec) +
  1889. Params->BaseDifferenceSec;
  1890. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1891. UnixTimeStamp -=
  1892. CurrentParams->CurrentDaylightDifferenceSec +
  1893. CurrentParams->BaseDifferenceSec;
  1894. }
  1895. FILETIME Result;
  1896. (*(__int64*)&(Result) = (__int64(UnixTimeStamp) + 11644473600LL) * 10000000LL);
  1897. return Result;
  1898. }
  1899. //---------------------------------------------------------------------------
  1900. TDateTime __fastcall FileTimeToDateTime(const FILETIME & FileTime)
  1901. {
  1902. // duplicated in DirView.pas
  1903. TDateTime Result;
  1904. // The 0xFFF... is sometime seen for invalid timestamps,
  1905. // it would cause failure in SystemTimeToDateTime below
  1906. if (FileTime.dwLowDateTime == std::numeric_limits<DWORD>::max())
  1907. {
  1908. Result = MinDateTime;
  1909. }
  1910. else
  1911. {
  1912. SYSTEMTIME SysTime;
  1913. if (!UsesDaylightHack())
  1914. {
  1915. SYSTEMTIME UniverzalSysTime;
  1916. FileTimeToSystemTime(&FileTime, &UniverzalSysTime);
  1917. SystemTimeToTzSpecificLocalTime(NULL, &UniverzalSysTime, &SysTime);
  1918. }
  1919. else
  1920. {
  1921. FILETIME LocalFileTime;
  1922. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1923. FileTimeToSystemTime(&LocalFileTime, &SysTime);
  1924. }
  1925. Result = SystemTimeToDateTimeVerbose(SysTime);
  1926. }
  1927. return Result;
  1928. }
  1929. //---------------------------------------------------------------------------
  1930. __int64 __fastcall ConvertTimestampToUnix(const FILETIME & FileTime,
  1931. TDSTMode DSTMode)
  1932. {
  1933. __int64 Result = ((*(__int64*)&(FileTime)) / 10000000LL - 11644473600LL);
  1934. if (UsesDaylightHack())
  1935. {
  1936. if ((DSTMode == dstmUnix) || (DSTMode == dstmKeep))
  1937. {
  1938. FILETIME LocalFileTime;
  1939. SYSTEMTIME SystemTime;
  1940. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1941. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1942. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1943. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1944. Result += (IsDateInDST(DateTime) ?
  1945. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1946. if (DSTMode == dstmKeep)
  1947. {
  1948. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1949. Result -= CurrentParams->CurrentDaylightDifferenceSec;
  1950. }
  1951. }
  1952. }
  1953. else
  1954. {
  1955. if (DSTMode == dstmWin)
  1956. {
  1957. FILETIME LocalFileTime;
  1958. SYSTEMTIME SystemTime;
  1959. FileTimeToLocalFileTime(&FileTime, &LocalFileTime);
  1960. FileTimeToSystemTime(&LocalFileTime, &SystemTime);
  1961. TDateTime DateTime = SystemTimeToDateTimeVerbose(SystemTime);
  1962. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1963. Result -= (IsDateInDST(DateTime) ?
  1964. Params->DaylightDifferenceSec : Params->StandardDifferenceSec);
  1965. }
  1966. }
  1967. return Result;
  1968. }
  1969. //---------------------------------------------------------------------------
  1970. TDateTime __fastcall ConvertTimestampToUTC(TDateTime DateTime)
  1971. {
  1972. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1973. DateTime += DSTDifferenceForTime(DateTime);
  1974. DateTime += Params->BaseDifference;
  1975. if (Params->DaylightHack)
  1976. {
  1977. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1978. DateTime += CurrentParams->CurrentDaylightDifference;
  1979. }
  1980. return DateTime;
  1981. }
  1982. //---------------------------------------------------------------------------
  1983. TDateTime __fastcall ConvertTimestampFromUTC(TDateTime DateTime)
  1984. {
  1985. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  1986. DateTime -= DSTDifferenceForTime(DateTime);
  1987. DateTime -= Params->BaseDifference;
  1988. if (Params->DaylightHack)
  1989. {
  1990. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  1991. DateTime -= CurrentParams->CurrentDaylightDifference;
  1992. }
  1993. return DateTime;
  1994. }
  1995. //---------------------------------------------------------------------------
  1996. __int64 __fastcall ConvertTimestampToUnixSafe(const FILETIME & FileTime,
  1997. TDSTMode DSTMode)
  1998. {
  1999. __int64 Result;
  2000. if ((FileTime.dwLowDateTime == 0) &&
  2001. (FileTime.dwHighDateTime == 0))
  2002. {
  2003. Result = ::DateTimeToUnix(Now());
  2004. }
  2005. else
  2006. {
  2007. Result = ConvertTimestampToUnix(FileTime, DSTMode);
  2008. }
  2009. return Result;
  2010. }
  2011. //---------------------------------------------------------------------------
  2012. double __fastcall DSTDifferenceForTime(TDateTime DateTime)
  2013. {
  2014. double Result;
  2015. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2016. if (IsDateInDST(DateTime))
  2017. {
  2018. Result = Params->DaylightDifference;
  2019. }
  2020. else
  2021. {
  2022. Result = Params->StandardDifference;
  2023. }
  2024. return Result;
  2025. }
  2026. //---------------------------------------------------------------------------
  2027. TDateTime __fastcall AdjustDateTimeFromUnix(TDateTime DateTime, TDSTMode DSTMode)
  2028. {
  2029. const TDateTimeParams * Params = GetDateTimeParams(DecodeYear(DateTime));
  2030. if (Params->DaylightHack)
  2031. {
  2032. if ((DSTMode == dstmWin) || (DSTMode == dstmUnix))
  2033. {
  2034. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2035. DateTime = DateTime - CurrentParams->CurrentDaylightDifference;
  2036. }
  2037. if (!IsDateInDST(DateTime))
  2038. {
  2039. if (DSTMode == dstmWin)
  2040. {
  2041. DateTime = DateTime - Params->DaylightDifference;
  2042. }
  2043. }
  2044. else
  2045. {
  2046. DateTime = DateTime - Params->StandardDifference;
  2047. }
  2048. }
  2049. else
  2050. {
  2051. if (DSTMode == dstmWin)
  2052. {
  2053. DateTime = DateTime + DSTDifferenceForTime(DateTime);
  2054. }
  2055. }
  2056. return DateTime;
  2057. }
  2058. //---------------------------------------------------------------------------
  2059. UnicodeString __fastcall FixedLenDateTimeFormat(const UnicodeString & Format)
  2060. {
  2061. UnicodeString Result = Format;
  2062. bool AsIs = false;
  2063. int Index = 1;
  2064. while (Index <= Result.Length())
  2065. {
  2066. wchar_t F = Result[Index];
  2067. if ((F == L'\'') || (F == L'\"'))
  2068. {
  2069. AsIs = !AsIs;
  2070. Index++;
  2071. }
  2072. else if (!AsIs && ((F == L'a') || (F == L'A')))
  2073. {
  2074. if (Result.SubString(Index, 5).LowerCase() == L"am/pm")
  2075. {
  2076. Index += 5;
  2077. }
  2078. else if (Result.SubString(Index, 3).LowerCase() == L"a/p")
  2079. {
  2080. Index += 3;
  2081. }
  2082. else if (Result.SubString(Index, 4).LowerCase() == L"ampm")
  2083. {
  2084. Index += 4;
  2085. }
  2086. else
  2087. {
  2088. Index++;
  2089. }
  2090. }
  2091. else
  2092. {
  2093. if (!AsIs && (wcschr(L"dDeEmMhHnNsS", F) != NULL) &&
  2094. ((Index == Result.Length()) || (Result[Index + 1] != F)))
  2095. {
  2096. Result.Insert(F, Index);
  2097. }
  2098. while ((Index <= Result.Length()) && (F == Result[Index]))
  2099. {
  2100. Index++;
  2101. }
  2102. }
  2103. }
  2104. return Result;
  2105. }
  2106. //---------------------------------------------------------------------------
  2107. UnicodeString __fastcall FormatTimeZone(long Sec)
  2108. {
  2109. TTimeSpan Span = TTimeSpan::FromSeconds(Sec);
  2110. UnicodeString Str;
  2111. if ((Span.Seconds == 0) && (Span.Minutes == 0))
  2112. {
  2113. Str = FORMAT(L"%d", (-Span.Hours));
  2114. }
  2115. else if (Span.Seconds == 0)
  2116. {
  2117. Str = FORMAT(L"%d:%2.2d", (-Span.Hours, abs(Span.Minutes)));
  2118. }
  2119. else
  2120. {
  2121. Str = FORMAT(L"%d:%2.2d:%2.2d", (-Span.Hours, abs(Span.Minutes), abs(Span.Seconds)));
  2122. }
  2123. Str = ((Span <= TTimeSpan::Zero) ? L"+" : L"") + Str;
  2124. return Str;
  2125. }
  2126. //---------------------------------------------------------------------------
  2127. UnicodeString __fastcall GetTimeZoneLogString()
  2128. {
  2129. const TDateTimeParams * CurrentParams = GetDateTimeParams(0);
  2130. UnicodeString Result =
  2131. FORMAT(L"Current: GMT%s", (FormatTimeZone(CurrentParams->CurrentDifferenceSec)));
  2132. if (!CurrentParams->HasDST())
  2133. {
  2134. Result += FORMAT(L" (%s), No DST", (CurrentParams->StandardName));
  2135. }
  2136. else
  2137. {
  2138. Result +=
  2139. FORMAT(L", Standard: GMT%s (%s), DST: GMT%s (%s), DST Start: %s, DST End: %s",
  2140. (FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->StandardDifferenceSec),
  2141. CurrentParams->StandardName,
  2142. FormatTimeZone(CurrentParams->BaseDifferenceSec + CurrentParams->DaylightDifferenceSec),
  2143. CurrentParams->DaylightName,
  2144. CurrentParams->DaylightDate.DateString(),
  2145. CurrentParams->StandardDate.DateString()));
  2146. }
  2147. return Result;
  2148. }
  2149. //---------------------------------------------------------------------------
  2150. bool __fastcall AdjustClockForDSTEnabled()
  2151. {
  2152. // Windows XP deletes the DisableAutoDaylightTimeSet value when it is off
  2153. // (the later versions set it to DynamicDaylightTimeDisabled to 0)
  2154. bool DynamicDaylightTimeDisabled = false;
  2155. TRegistry * Registry = new TRegistry(KEY_READ);
  2156. try
  2157. {
  2158. Registry->RootKey = HKEY_LOCAL_MACHINE;
  2159. if (Registry->OpenKey(L"SYSTEM", false) &&
  2160. Registry->OpenKey(L"CurrentControlSet", false) &&
  2161. Registry->OpenKey(L"Control", false) &&
  2162. Registry->OpenKey(L"TimeZoneInformation", false))
  2163. {
  2164. if (Registry->ValueExists(L"DynamicDaylightTimeDisabled"))
  2165. {
  2166. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DynamicDaylightTimeDisabled");
  2167. }
  2168. // WORKAROUND
  2169. // Windows XP equivalent
  2170. else if (Registry->ValueExists(L"DisableAutoDaylightTimeSet"))
  2171. {
  2172. DynamicDaylightTimeDisabled = Registry->ReadBool(L"DisableAutoDaylightTimeSet");
  2173. }
  2174. }
  2175. delete Registry;
  2176. }
  2177. catch(...)
  2178. {
  2179. }
  2180. return !DynamicDaylightTimeDisabled;
  2181. }
  2182. //---------------------------------------------------------------------------
  2183. UnicodeString __fastcall StandardDatestamp()
  2184. {
  2185. return FormatDateTime(L"yyyy'-'mm'-'dd", ConvertTimestampToUTC(Now()));
  2186. }
  2187. //---------------------------------------------------------------------------
  2188. UnicodeString __fastcall StandardTimestamp(const TDateTime & DateTime)
  2189. {
  2190. return FormatDateTime(L"yyyy'-'mm'-'dd'T'hh':'nn':'ss'.'zzz'Z'", ConvertTimestampToUTC(DateTime));
  2191. }
  2192. //---------------------------------------------------------------------------
  2193. UnicodeString __fastcall StandardTimestamp()
  2194. {
  2195. return StandardTimestamp(Now());
  2196. }
  2197. //---------------------------------------------------------------------------
  2198. static TDateTime TwoSeconds(0, 0, 2, 0);
  2199. int __fastcall CompareFileTime(TDateTime T1, TDateTime T2)
  2200. {
  2201. // "FAT" time precision
  2202. // (when one time is seconds-precision and other is millisecond-precision,
  2203. // we may have times like 12:00:00.000 and 12:00:01.999, which should
  2204. // be treated the same)
  2205. int Result;
  2206. if (T1 == T2)
  2207. {
  2208. // just optimization
  2209. Result = 0;
  2210. }
  2211. else if ((T1 < T2) && (T2 - T1 >= TwoSeconds))
  2212. {
  2213. Result = -1;
  2214. }
  2215. else if ((T1 > T2) && (T1 - T2 >= TwoSeconds))
  2216. {
  2217. Result = 1;
  2218. }
  2219. else
  2220. {
  2221. Result = 0;
  2222. }
  2223. return Result;
  2224. }
  2225. //---------------------------------------------------------------------------
  2226. int __fastcall TimeToMSec(TDateTime T)
  2227. {
  2228. return int(Round(double(T) * double(MSecsPerDay)));
  2229. }
  2230. //---------------------------------------------------------------------------
  2231. int __fastcall TimeToSeconds(TDateTime T)
  2232. {
  2233. return TimeToMSec(T) / MSecsPerSec;
  2234. }
  2235. //---------------------------------------------------------------------------
  2236. int __fastcall TimeToMinutes(TDateTime T)
  2237. {
  2238. return TimeToSeconds(T) / SecsPerMin;
  2239. }
  2240. //---------------------------------------------------------------------------
  2241. static bool __fastcall DoRecursiveDeleteFile(
  2242. const UnicodeString FileName, bool ToRecycleBin, UnicodeString & ErrorPath, int & Deleted)
  2243. {
  2244. bool Result;
  2245. Deleted = 0;
  2246. UnicodeString AErrorPath = FileName;
  2247. if (!ToRecycleBin)
  2248. {
  2249. TSearchRecChecked SearchRec;
  2250. Result = FileSearchRec(FileName, SearchRec);
  2251. if (Result)
  2252. {
  2253. if (!SearchRec.IsDirectory())
  2254. {
  2255. Result = DeleteFile(ApiPath(FileName));
  2256. if (Result)
  2257. {
  2258. Deleted++;
  2259. }
  2260. }
  2261. else
  2262. {
  2263. Result = (FindFirstUnchecked(FileName + L"\\*", faAnyFile, SearchRec) == 0);
  2264. if (Result)
  2265. {
  2266. try
  2267. {
  2268. do
  2269. {
  2270. UnicodeString FileName2 = FileName + L"\\" + SearchRec.Name;
  2271. if (SearchRec.IsDirectory())
  2272. {
  2273. if (SearchRec.IsRealFile())
  2274. {
  2275. Result = DoRecursiveDeleteFile(FileName2, DebugAlwaysFalse(ToRecycleBin), AErrorPath, Deleted);
  2276. }
  2277. }
  2278. else
  2279. {
  2280. Result = DeleteFile(ApiPath(FileName2));
  2281. if (!Result)
  2282. {
  2283. AErrorPath = FileName2;
  2284. }
  2285. else
  2286. {
  2287. Deleted++;
  2288. }
  2289. }
  2290. }
  2291. while (Result && (FindNextUnchecked(SearchRec) == 0));
  2292. }
  2293. __finally
  2294. {
  2295. FindClose(SearchRec);
  2296. }
  2297. if (Result)
  2298. {
  2299. Result = RemoveDir(ApiPath(FileName));
  2300. if (Result)
  2301. {
  2302. Deleted++;
  2303. }
  2304. }
  2305. }
  2306. }
  2307. }
  2308. }
  2309. else
  2310. {
  2311. SHFILEOPSTRUCT Data;
  2312. memset(&Data, 0, sizeof(Data));
  2313. Data.hwnd = NULL;
  2314. Data.wFunc = FO_DELETE;
  2315. // SHFileOperation does not support long paths anyway
  2316. UnicodeString FileList(ApiPath(FileName));
  2317. FileList.SetLength(FileList.Length() + 2);
  2318. FileList[FileList.Length() - 1] = L'\0';
  2319. FileList[FileList.Length()] = L'\0';
  2320. Data.pFrom = FileList.c_str();
  2321. Data.pTo = L"\0\0"; // this will actually give one null more than needed
  2322. Data.fFlags = FOF_NOCONFIRMATION | FOF_RENAMEONCOLLISION | FOF_NOCONFIRMMKDIR |
  2323. FOF_NOERRORUI | FOF_SILENT;
  2324. if (DebugAlwaysTrue(ToRecycleBin))
  2325. {
  2326. Data.fFlags |= FOF_ALLOWUNDO;
  2327. }
  2328. int ErrorCode = SHFileOperation(&Data);
  2329. Result = (ErrorCode == 0);
  2330. if (!Result)
  2331. {
  2332. // according to MSDN, SHFileOperation may return following non-Win32
  2333. // error codes
  2334. if (((ErrorCode >= 0x71) && (ErrorCode <= 0x88)) ||
  2335. (ErrorCode == 0xB7) || (ErrorCode == 0x402) || (ErrorCode == 0x10000) ||
  2336. (ErrorCode == 0x10074))
  2337. {
  2338. ErrorCode = 0;
  2339. }
  2340. SetLastError(ErrorCode);
  2341. }
  2342. if (Result)
  2343. {
  2344. Deleted = 1;
  2345. }
  2346. }
  2347. if (!Result)
  2348. {
  2349. ErrorPath = AErrorPath;
  2350. }
  2351. return Result;
  2352. }
  2353. //---------------------------------------------------------------------------
  2354. bool __fastcall RecursiveDeleteFile(const UnicodeString & FileName, bool ToRecycleBin)
  2355. {
  2356. UnicodeString ErrorPath; // unused
  2357. int Deleted;
  2358. bool Result = DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath, Deleted);
  2359. return Result;
  2360. }
  2361. //---------------------------------------------------------------------------
  2362. int __fastcall RecursiveDeleteFileChecked(const UnicodeString & FileName, bool ToRecycleBin)
  2363. {
  2364. UnicodeString ErrorPath;
  2365. int Deleted;
  2366. if (!DoRecursiveDeleteFile(FileName, ToRecycleBin, ErrorPath, Deleted))
  2367. {
  2368. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (ErrorPath)));
  2369. }
  2370. return Deleted;
  2371. }
  2372. //---------------------------------------------------------------------------
  2373. void __fastcall DeleteFileChecked(const UnicodeString & FileName)
  2374. {
  2375. if (!DeleteFile(ApiPath(FileName)))
  2376. {
  2377. throw EOSExtException(FMTLOAD(DELETE_LOCAL_FILE_ERROR, (FileName)));
  2378. }
  2379. }
  2380. //---------------------------------------------------------------------------
  2381. unsigned int __fastcall CancelAnswer(unsigned int Answers)
  2382. {
  2383. unsigned int Result;
  2384. if ((Answers & qaCancel) != 0)
  2385. {
  2386. Result = qaCancel;
  2387. }
  2388. else if ((Answers & qaNo) != 0)
  2389. {
  2390. Result = qaNo;
  2391. }
  2392. else if ((Answers & qaAbort) != 0)
  2393. {
  2394. Result = qaAbort;
  2395. }
  2396. else if ((Answers & qaOK) != 0)
  2397. {
  2398. Result = qaOK;
  2399. }
  2400. else
  2401. {
  2402. DebugFail();
  2403. Result = qaCancel;
  2404. }
  2405. return Result;
  2406. }
  2407. //---------------------------------------------------------------------------
  2408. unsigned int __fastcall AbortAnswer(unsigned int Answers)
  2409. {
  2410. unsigned int Result;
  2411. if (FLAGSET(Answers, qaAbort))
  2412. {
  2413. Result = qaAbort;
  2414. }
  2415. else
  2416. {
  2417. Result = CancelAnswer(Answers);
  2418. }
  2419. return Result;
  2420. }
  2421. //---------------------------------------------------------------------------
  2422. unsigned int __fastcall ContinueAnswer(unsigned int Answers)
  2423. {
  2424. unsigned int Result;
  2425. if (FLAGSET(Answers, qaSkip))
  2426. {
  2427. Result = qaSkip;
  2428. }
  2429. else if (FLAGSET(Answers, qaIgnore))
  2430. {
  2431. Result = qaIgnore;
  2432. }
  2433. else if (FLAGSET(Answers, qaYes))
  2434. {
  2435. Result = qaYes;
  2436. }
  2437. else if (FLAGSET(Answers, qaOK))
  2438. {
  2439. Result = qaOK;
  2440. }
  2441. else if (FLAGSET(Answers, qaRetry))
  2442. {
  2443. Result = qaRetry;
  2444. }
  2445. else
  2446. {
  2447. Result = CancelAnswer(Answers);
  2448. }
  2449. return Result;
  2450. }
  2451. //---------------------------------------------------------------------------
  2452. TLibModule * __fastcall FindModule(void * Instance)
  2453. {
  2454. TLibModule * CurModule;
  2455. CurModule = reinterpret_cast<TLibModule*>(LibModuleList);
  2456. while (CurModule)
  2457. {
  2458. if (CurModule->Instance == (unsigned)Instance)
  2459. {
  2460. break;
  2461. }
  2462. else
  2463. {
  2464. CurModule = CurModule->Next;
  2465. }
  2466. }
  2467. return CurModule;
  2468. }
  2469. //---------------------------------------------------------------------------
  2470. static UnicodeString __fastcall DoLoadStrFrom(HINSTANCE Module, int Ident, unsigned int MaxLength)
  2471. {
  2472. UnicodeString Result;
  2473. Result.SetLength(MaxLength);
  2474. int Length = LoadString(Module, Ident, Result.c_str(), MaxLength);
  2475. Result.SetLength(Length);
  2476. return Result;
  2477. }
  2478. //---------------------------------------------------------------------------
  2479. UnicodeString __fastcall LoadStrFrom(HINSTANCE Module, int Ident)
  2480. {
  2481. // 1024 = what VCL LoadStr limits the string to
  2482. return DoLoadStrFrom(Module, Ident, 1024);
  2483. }
  2484. //---------------------------------------------------------------------------
  2485. UnicodeString __fastcall LoadStr(int Ident, unsigned int MaxLength)
  2486. {
  2487. TLibModule * MainModule = FindModule(HInstance);
  2488. DebugAssert(MainModule != NULL);
  2489. return DoLoadStrFrom((HINSTANCE)MainModule->ResInstance, Ident, MaxLength);
  2490. }
  2491. //---------------------------------------------------------------------------
  2492. UnicodeString __fastcall LoadStrPart(int Ident, int Part)
  2493. {
  2494. UnicodeString Result;
  2495. UnicodeString Str = LoadStr(Ident);
  2496. while (Part > 0)
  2497. {
  2498. Result = CutToChar(Str, L'|', false);
  2499. Part--;
  2500. }
  2501. return Result;
  2502. }
  2503. //---------------------------------------------------------------------------
  2504. UnicodeString __fastcall DecodeUrlChars(UnicodeString S)
  2505. {
  2506. int i = 1;
  2507. while (i <= S.Length())
  2508. {
  2509. switch (S[i])
  2510. {
  2511. case L'+':
  2512. S[i] = ' ';
  2513. break;
  2514. case L'%':
  2515. {
  2516. UnicodeString Hex;
  2517. while ((i + 2 <= S.Length()) && (S[i] == L'%') &&
  2518. IsHex(S[i + 1]) && IsHex(S[i + 2]))
  2519. {
  2520. Hex += S.SubString(i + 1, 2);
  2521. S.Delete(i, 3);
  2522. }
  2523. if (!Hex.IsEmpty())
  2524. {
  2525. RawByteString Bytes = HexToBytes(Hex);
  2526. UnicodeString Chars(UTF8ToString(Bytes));
  2527. S.Insert(Chars, i);
  2528. i += Chars.Length() - 1;
  2529. }
  2530. }
  2531. break;
  2532. }
  2533. i++;
  2534. }
  2535. return S;
  2536. }
  2537. //---------------------------------------------------------------------------
  2538. UnicodeString __fastcall DoEncodeUrl(UnicodeString S, const UnicodeString & DoNotEncode)
  2539. {
  2540. int Index = 1;
  2541. while (Index <= S.Length())
  2542. {
  2543. wchar_t C = S[Index];
  2544. if (IsLetter(C) ||
  2545. IsDigit(C) ||
  2546. (C == L'_') || (C == L'-') || (C == L'.') || (C == L'*') ||
  2547. (DoNotEncode.Pos(C) > 0))
  2548. {
  2549. Index++;
  2550. }
  2551. else
  2552. {
  2553. UTF8String UtfS(S.SubString(Index, 1));
  2554. UnicodeString H;
  2555. for (int Index2 = 1; Index2 <= UtfS.Length(); Index2++)
  2556. {
  2557. H += L"%" + ByteToHex(static_cast<unsigned char>(UtfS[Index2]));
  2558. }
  2559. S.Delete(Index, 1);
  2560. S.Insert(H, Index);
  2561. Index += H.Length();
  2562. }
  2563. }
  2564. return S;
  2565. }
  2566. //---------------------------------------------------------------------------
  2567. UnicodeString __fastcall EncodeUrlString(UnicodeString S, const UnicodeString & DoNotEncode)
  2568. {
  2569. return DoEncodeUrl(S, DoNotEncode);
  2570. }
  2571. //---------------------------------------------------------------------------
  2572. UnicodeString __fastcall EncodeUrlPath(UnicodeString S)
  2573. {
  2574. return DoEncodeUrl(S, L"/");
  2575. }
  2576. //---------------------------------------------------------------------------
  2577. UnicodeString __fastcall AppendUrlParams(UnicodeString AURL, UnicodeString Params)
  2578. {
  2579. // see also TWebHelpSystem::ShowHelp
  2580. const wchar_t FragmentSeparator = L'#';
  2581. UnicodeString URL = CutToChar(AURL, FragmentSeparator, false);
  2582. if (URL.Pos(L"?") == 0)
  2583. {
  2584. URL += L"?";
  2585. }
  2586. else
  2587. {
  2588. URL += L"&";
  2589. }
  2590. URL += Params;
  2591. AddToList(URL, AURL, FragmentSeparator);
  2592. return URL;
  2593. }
  2594. //---------------------------------------------------------------------------
  2595. UnicodeString __fastcall ExtractFileNameFromUrl(const UnicodeString & Url)
  2596. {
  2597. UnicodeString Result = Url;
  2598. int P = Result.Pos(L"?");
  2599. if (P > 0)
  2600. {
  2601. Result.SetLength(P - 1);
  2602. }
  2603. P = Result.LastDelimiter("/");
  2604. if (DebugAlwaysTrue(P > 0))
  2605. {
  2606. Result.Delete(1, P);
  2607. }
  2608. return Result;
  2609. }
  2610. //---------------------------------------------------------------------------
  2611. UnicodeString __fastcall EscapeHotkey(const UnicodeString & Caption)
  2612. {
  2613. return ReplaceStr(Caption, L"&", L"&&");
  2614. }
  2615. //---------------------------------------------------------------------------
  2616. // duplicated in console's Main.cpp
  2617. static bool __fastcall DoCutToken(UnicodeString & Str, UnicodeString & Token,
  2618. UnicodeString * RawToken, UnicodeString * Separator, bool EscapeQuotesInQuotesOnly)
  2619. {
  2620. bool Result;
  2621. Token = L"";
  2622. // inspired by Putty's sftp_getcmd() from PSFTP.C
  2623. int Index = 1;
  2624. while ((Index <= Str.Length()) &&
  2625. ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2626. {
  2627. Index++;
  2628. }
  2629. if (Index <= Str.Length())
  2630. {
  2631. bool Quoting = false;
  2632. while (Index <= Str.Length())
  2633. {
  2634. if (!Quoting && ((Str[Index] == L' ') || (Str[Index] == L'\t')))
  2635. {
  2636. break;
  2637. }
  2638. // With EscapeQuotesInQuotesOnly we escape quotes only within quotes
  2639. // otherwise the "" means " (quote), but it should mean empty string.
  2640. else if ((Str[Index] == L'"') && (Index + 1 <= Str.Length()) &&
  2641. (Str[Index + 1] == L'"') && (!EscapeQuotesInQuotesOnly || Quoting))
  2642. {
  2643. Index += 2;
  2644. Token += L'"';
  2645. }
  2646. else if (Str[Index] == L'"')
  2647. {
  2648. Index++;
  2649. Quoting = !Quoting;
  2650. }
  2651. else
  2652. {
  2653. Token += Str[Index];
  2654. Index++;
  2655. }
  2656. }
  2657. if (RawToken != NULL)
  2658. {
  2659. (*RawToken) = Str.SubString(1, Index - 1);
  2660. }
  2661. if (Index <= Str.Length())
  2662. {
  2663. if (Separator != NULL)
  2664. {
  2665. *Separator = Str.SubString(Index, 1);
  2666. }
  2667. Index++;
  2668. }
  2669. else
  2670. {
  2671. if (Separator != NULL)
  2672. {
  2673. *Separator = UnicodeString();
  2674. }
  2675. }
  2676. Str = Str.SubString(Index, Str.Length());
  2677. Result = true;
  2678. }
  2679. else
  2680. {
  2681. Result = false;
  2682. Str = L"";
  2683. }
  2684. return Result;
  2685. }
  2686. //---------------------------------------------------------------------------
  2687. bool __fastcall CutToken(UnicodeString & Str, UnicodeString & Token,
  2688. UnicodeString * RawToken, UnicodeString * Separator)
  2689. {
  2690. return DoCutToken(Str, Token, RawToken, Separator, false);
  2691. }
  2692. //---------------------------------------------------------------------------
  2693. bool __fastcall CutTokenEx(UnicodeString & Str, UnicodeString & Token,
  2694. UnicodeString * RawToken, UnicodeString * Separator)
  2695. {
  2696. return DoCutToken(Str, Token, RawToken, Separator, true);
  2697. }
  2698. //---------------------------------------------------------------------------
  2699. void __fastcall AddToList(UnicodeString & List, const UnicodeString & Value, const UnicodeString & Delimiter)
  2700. {
  2701. if (!Value.IsEmpty())
  2702. {
  2703. if (!List.IsEmpty() &&
  2704. ((List.Length() < Delimiter.Length()) ||
  2705. (List.SubString(List.Length() - Delimiter.Length() + 1, Delimiter.Length()) != Delimiter)))
  2706. {
  2707. List += Delimiter;
  2708. }
  2709. List += Value;
  2710. }
  2711. }
  2712. //---------------------------------------------------------------------------
  2713. bool __fastcall IsWinVista()
  2714. {
  2715. // Vista is 6.0
  2716. // Win XP is 5.1
  2717. // There also 5.2, what is Windows 2003 or Windows XP 64bit
  2718. // (we consider it WinXP for now)
  2719. return CheckWin32Version(6, 0);
  2720. }
  2721. //---------------------------------------------------------------------------
  2722. bool __fastcall IsWin7()
  2723. {
  2724. return CheckWin32Version(6, 1);
  2725. }
  2726. //---------------------------------------------------------------------------
  2727. bool __fastcall IsWin8()
  2728. {
  2729. return CheckWin32Version(6, 2);
  2730. }
  2731. //---------------------------------------------------------------------------
  2732. bool __fastcall IsWin10()
  2733. {
  2734. return CheckWin32Version(10, 0);
  2735. }
  2736. //---------------------------------------------------------------------------
  2737. bool __fastcall IsWine()
  2738. {
  2739. HMODULE NtDll = GetModuleHandle(L"ntdll.dll");
  2740. return
  2741. DebugAlwaysTrue(NtDll != NULL) &&
  2742. (GetProcAddress(NtDll, "wine_get_version") != NULL);
  2743. }
  2744. //---------------------------------------------------------------------------
  2745. int GIsUWP = -1;
  2746. //---------------------------------------------------------------------------
  2747. bool __fastcall IsUWP()
  2748. {
  2749. if (GIsUWP < 0)
  2750. {
  2751. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  2752. typedef LONG WINAPI (* GetPackageFamilyNameProc)(HANDLE hProcess, UINT32 *packageFamilyNameLength, PWSTR packageFamilyName);
  2753. GetPackageFamilyNameProc GetPackageFamilyName =
  2754. (GetPackageFamilyNameProc)GetProcAddress(Kernel32, "GetPackageFamilyName");
  2755. UINT32 Len = 0;
  2756. bool Result =
  2757. (GetPackageFamilyName != NULL) &&
  2758. (GetPackageFamilyName(GetCurrentProcess(), &Len, NULL) == ERROR_INSUFFICIENT_BUFFER);
  2759. GIsUWP = (Result ? 1 : 0);
  2760. }
  2761. return (GIsUWP > 0);
  2762. }
  2763. //---------------------------------------------------------------------------
  2764. LCID __fastcall GetDefaultLCID()
  2765. {
  2766. return GetUserDefaultLCID();
  2767. }
  2768. //---------------------------------------------------------------------------
  2769. static UnicodeString ADefaultEncodingName;
  2770. UnicodeString __fastcall DefaultEncodingName()
  2771. {
  2772. if (ADefaultEncodingName.IsEmpty())
  2773. {
  2774. CPINFOEX Info;
  2775. GetCPInfoEx(CP_ACP, 0, &Info);
  2776. ADefaultEncodingName = Info.CodePageName;
  2777. }
  2778. return ADefaultEncodingName;
  2779. }
  2780. //---------------------------------------------------------------------------
  2781. bool _fastcall GetWindowsProductType(DWORD & Type)
  2782. {
  2783. bool Result;
  2784. HINSTANCE Kernel32 = GetModuleHandle(kernel32);
  2785. typedef BOOL WINAPI (* TGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD);
  2786. TGetProductInfo GetProductInfo =
  2787. (TGetProductInfo)GetProcAddress(Kernel32, "GetProductInfo");
  2788. if (GetProductInfo == NULL)
  2789. {
  2790. Result = false;
  2791. }
  2792. else
  2793. {
  2794. GetProductInfo(Win32MajorVersion, Win32MinorVersion, 0, 0, &Type);
  2795. Result = true;
  2796. }
  2797. return Result;
  2798. }
  2799. //---------------------------------------------------------------------------
  2800. UnicodeString __fastcall WindowsProductName()
  2801. {
  2802. UnicodeString Result;
  2803. TRegistry * Registry = new TRegistry(KEY_READ);
  2804. try
  2805. {
  2806. Registry->RootKey = HKEY_LOCAL_MACHINE;
  2807. if (Registry->OpenKey(L"SOFTWARE", false) &&
  2808. Registry->OpenKey(L"Microsoft", false) &&
  2809. Registry->OpenKey(L"Windows NT", false) &&
  2810. Registry->OpenKey(L"CurrentVersion", false))
  2811. {
  2812. Result = Registry->ReadString(L"ProductName");
  2813. }
  2814. delete Registry;
  2815. }
  2816. catch(...)
  2817. {
  2818. }
  2819. return Result;
  2820. }
  2821. //---------------------------------------------------------------------------
  2822. static OSVERSIONINFO __fastcall GetWindowsVersion()
  2823. {
  2824. OSVERSIONINFO Result;
  2825. memset(&Result, 0, sizeof(Result));
  2826. Result.dwOSVersionInfoSize = sizeof(Result);
  2827. // Cannot use the VCL Win32MajorVersion+Win32MinorVersion+Win32BuildNumber as
  2828. // on Windows 10 due to some hacking in InitPlatformId, the Win32BuildNumber is lost
  2829. GetVersionEx(&Result);
  2830. return Result;
  2831. }
  2832. //---------------------------------------------------------------------------
  2833. int __fastcall GetWindowsBuild()
  2834. {
  2835. return GetWindowsVersion().dwBuildNumber;
  2836. }
  2837. //---------------------------------------------------------------------------
  2838. UnicodeString __fastcall WindowsVersion()
  2839. {
  2840. OSVERSIONINFO OSVersionInfo = GetWindowsVersion();
  2841. UnicodeString Result = FORMAT(L"%d.%d.%d", (int(OSVersionInfo.dwMajorVersion), int(OSVersionInfo.dwMinorVersion), int(OSVersionInfo.dwBuildNumber)));
  2842. return Result;
  2843. }
  2844. //---------------------------------------------------------------------------
  2845. UnicodeString __fastcall WindowsVersionLong()
  2846. {
  2847. UnicodeString Result = WindowsVersion();
  2848. AddToList(Result, Win32CSDVersion, L" ");
  2849. return Result;
  2850. }
  2851. //---------------------------------------------------------------------------
  2852. bool __fastcall IsDirectoryWriteable(const UnicodeString & Path)
  2853. {
  2854. UnicodeString FileName =
  2855. IncludeTrailingPathDelimiter(Path) +
  2856. FORMAT(L"wscp_%s_%d.tmp", (FormatDateTime(L"nnzzz", Now()), int(GetCurrentProcessId())));
  2857. HANDLE Handle = CreateFile(ApiPath(FileName).c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
  2858. CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, 0);
  2859. bool Result = (Handle != INVALID_HANDLE_VALUE);
  2860. if (Result)
  2861. {
  2862. CloseHandle(Handle);
  2863. }
  2864. return Result;
  2865. }
  2866. //---------------------------------------------------------------------------
  2867. UnicodeString __fastcall FormatNumber(__int64 Number)
  2868. {
  2869. return FormatFloat(L"#,##0", Number);
  2870. }
  2871. //---------------------------------------------------------------------------
  2872. // simple alternative to FormatBytes
  2873. UnicodeString __fastcall FormatSize(__int64 Size)
  2874. {
  2875. return FormatNumber(Size);
  2876. }
  2877. //---------------------------------------------------------------------------
  2878. UnicodeString __fastcall FormatDateTimeSpan(const UnicodeString TimeFormat, TDateTime DateTime)
  2879. {
  2880. UnicodeString Result;
  2881. if (int(DateTime) > 0)
  2882. {
  2883. Result = IntToStr(int(DateTime)) + L", ";
  2884. }
  2885. // days are decremented, because when there are to many of them,
  2886. // "integer overflow" error occurs
  2887. Result += FormatDateTime(TimeFormat, DateTime - int(DateTime));
  2888. return Result;
  2889. }
  2890. //---------------------------------------------------------------------------
  2891. UnicodeString __fastcall ExtractFileBaseName(const UnicodeString & Path)
  2892. {
  2893. return ChangeFileExt(ExtractFileName(Path), L"");
  2894. }
  2895. //---------------------------------------------------------------------------
  2896. TStringList * __fastcall TextToStringList(const UnicodeString & Text)
  2897. {
  2898. std::unique_ptr<TStringList> List(new TStringList());
  2899. List->Text = Text;
  2900. return List.release();
  2901. }
  2902. //---------------------------------------------------------------------------
  2903. UnicodeString __fastcall StringsToText(TStrings * Strings)
  2904. {
  2905. UnicodeString Result;
  2906. if (Strings->Count == 1)
  2907. {
  2908. Result = Strings->Strings[0];
  2909. }
  2910. else
  2911. {
  2912. Result = Strings->Text;
  2913. }
  2914. return Result;
  2915. }
  2916. //---------------------------------------------------------------------------
  2917. TStrings * __fastcall CloneStrings(TStrings * Strings)
  2918. {
  2919. std::unique_ptr<TStringList> List(new TStringList());
  2920. List->AddStrings(Strings);
  2921. return List.release();
  2922. }
  2923. //---------------------------------------------------------------------------
  2924. UnicodeString __fastcall TrimVersion(UnicodeString Version)
  2925. {
  2926. while ((Version.Pos(L".") != Version.LastDelimiter(L".")) &&
  2927. (Version.SubString(Version.Length() - 1, 2) == L".0"))
  2928. {
  2929. Version.SetLength(Version.Length() - 2);
  2930. }
  2931. return Version;
  2932. }
  2933. //---------------------------------------------------------------------------
  2934. UnicodeString __fastcall FormatVersion(int MajovVersion, int MinorVersion, int Release)
  2935. {
  2936. return
  2937. TrimVersion(FORMAT(L"%d.%d.%d",
  2938. (MajovVersion, MinorVersion, Release)));
  2939. }
  2940. //---------------------------------------------------------------------------
  2941. TFormatSettings __fastcall GetEngFormatSettings()
  2942. {
  2943. return TFormatSettings::Create((TLocaleID)1033);
  2944. }
  2945. //---------------------------------------------------------------------------
  2946. int __fastcall ParseShortEngMonthName(const UnicodeString & MonthStr)
  2947. {
  2948. TFormatSettings FormatSettings = GetEngFormatSettings();
  2949. return IndexStr(MonthStr, FormatSettings.ShortMonthNames, FormatSettings.ShortMonthNames.Size()) + 1;
  2950. }
  2951. //---------------------------------------------------------------------------
  2952. TStringList * __fastcall CreateSortedStringList(bool CaseSensitive, System::Types::TDuplicates Duplicates)
  2953. {
  2954. TStringList * Result = new TStringList();
  2955. Result->CaseSensitive = CaseSensitive;
  2956. Result->Sorted = true;
  2957. Result->Duplicates = Duplicates;
  2958. return Result;
  2959. }
  2960. //---------------------------------------------------------------------------
  2961. static UnicodeString __fastcall NormalizeIdent(UnicodeString Ident)
  2962. {
  2963. int Index = 1;
  2964. while (Index <= Ident.Length())
  2965. {
  2966. if (Ident[Index] == L'-')
  2967. {
  2968. Ident.Delete(Index, 1);
  2969. }
  2970. else
  2971. {
  2972. Index++;
  2973. }
  2974. }
  2975. return Ident;
  2976. }
  2977. //---------------------------------------------------------------------------
  2978. UnicodeString __fastcall FindIdent(const UnicodeString & Ident, TStrings * Idents)
  2979. {
  2980. UnicodeString NormalizedIdent(NormalizeIdent(Ident));
  2981. for (int Index = 0; Index < Idents->Count; Index++)
  2982. {
  2983. if (SameText(NormalizedIdent, NormalizeIdent(Idents->Strings[Index])))
  2984. {
  2985. return Idents->Strings[Index];
  2986. }
  2987. }
  2988. return Ident;
  2989. }
  2990. //---------------------------------------------------------------------------
  2991. static UnicodeString __fastcall GetTlsErrorStr(int Err)
  2992. {
  2993. char * Buffer = new char[512];
  2994. ERR_error_string(Err, Buffer);
  2995. // not sure about the UTF8
  2996. return UnicodeString(UTF8String(Buffer));
  2997. }
  2998. //---------------------------------------------------------------------------
  2999. static FILE * __fastcall OpenCertificate(const UnicodeString & Path)
  3000. {
  3001. FILE * Result = _wfopen(ApiPath(Path).c_str(), L"rb");
  3002. if (Result == NULL)
  3003. {
  3004. int Error = errno;
  3005. throw EOSExtException(MainInstructions(FMTLOAD(CERTIFICATE_OPEN_ERROR, (Path))), Error);
  3006. }
  3007. return Result;
  3008. }
  3009. //---------------------------------------------------------------------------
  3010. struct TPemPasswordCallbackData
  3011. {
  3012. UnicodeString * Passphrase;
  3013. };
  3014. //---------------------------------------------------------------------------
  3015. static int PemPasswordCallback(char * Buf, int Size, int /*RWFlag*/, void * UserData)
  3016. {
  3017. TPemPasswordCallbackData & Data = *reinterpret_cast<TPemPasswordCallbackData *>(UserData);
  3018. UTF8String UtfPassphrase = UTF8String(*Data.Passphrase);
  3019. strncpy(Buf, UtfPassphrase.c_str(), Size);
  3020. Shred(UtfPassphrase);
  3021. Buf[Size - 1] = '\0';
  3022. return strlen(Buf);
  3023. }
  3024. //---------------------------------------------------------------------------
  3025. static bool __fastcall IsTlsPassphraseError(int Error, bool HasPassphrase)
  3026. {
  3027. int ErrorLib = ERR_GET_LIB(Error);
  3028. int ErrorReason = ERR_GET_REASON(Error);
  3029. bool Result =
  3030. ((ErrorLib == ERR_LIB_PKCS12) &&
  3031. (ErrorReason == PKCS12_R_MAC_VERIFY_FAILURE)) ||
  3032. ((ErrorLib == ERR_LIB_PEM) &&
  3033. (ErrorReason == PEM_R_BAD_PASSWORD_READ)) ||
  3034. (HasPassphrase && (ERR_LIB_EVP == ERR_LIB_EVP) &&
  3035. ((ErrorReason == PEM_R_BAD_DECRYPT) || (ErrorReason == PEM_R_BAD_BASE64_DECODE)));
  3036. return Result;
  3037. }
  3038. //---------------------------------------------------------------------------
  3039. static void __fastcall ThrowTlsCertificateErrorIgnorePassphraseErrors(const UnicodeString & Path, bool HasPassphrase)
  3040. {
  3041. int Error = ERR_get_error();
  3042. if (!IsTlsPassphraseError(Error, HasPassphrase))
  3043. {
  3044. throw ExtException(MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (Path))), GetTlsErrorStr(Error));
  3045. }
  3046. }
  3047. //---------------------------------------------------------------------------
  3048. void __fastcall ParseCertificate(const UnicodeString & Path,
  3049. const UnicodeString & Passphrase, X509 *& Certificate, EVP_PKEY *& PrivateKey,
  3050. bool & WrongPassphrase)
  3051. {
  3052. Certificate = NULL;
  3053. PrivateKey = NULL;
  3054. bool HasPassphrase = !Passphrase.IsEmpty();
  3055. FILE * File;
  3056. // Inspired by neon's ne_ssl_clicert_read
  3057. File = OpenCertificate(Path);
  3058. // openssl pkcs12 -inkey cert.pem -in cert.crt -export -out cert.pfx
  3059. // Binary file
  3060. PKCS12 * Pkcs12 = d2i_PKCS12_fp(File, NULL);
  3061. fclose(File);
  3062. if (Pkcs12 != NULL)
  3063. {
  3064. // Modeled after OPENSSL_asc2uni (reversed bitness to what UnicodeString/wchar_t use)
  3065. std::vector<char> Buf;
  3066. Buf.resize(Passphrase.Length() * sizeof(wchar_t) + sizeof(wchar_t));
  3067. for (int Index = 0; Index <= Passphrase.Length(); Index++)
  3068. {
  3069. Buf[(Index * 2)] = (Passphrase.c_str()[Index] >> 8);
  3070. Buf[(Index * 2) + 1] = (Passphrase.c_str()[Index] & 0x00FF);
  3071. }
  3072. bool Result =
  3073. (PKCS12_parse(Pkcs12, &Buf[0], &PrivateKey, &Certificate, NULL) == 1);
  3074. PKCS12_free(Pkcs12);
  3075. if (!Result)
  3076. {
  3077. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  3078. WrongPassphrase = true;
  3079. }
  3080. }
  3081. else
  3082. {
  3083. ERR_clear_error();
  3084. TPemPasswordCallbackData CallbackUserData;
  3085. // PemPasswordCallback never writes to the .Passphrase
  3086. CallbackUserData.Passphrase = const_cast<UnicodeString *>(&Passphrase);
  3087. File = OpenCertificate(Path);
  3088. // Encrypted:
  3089. // openssl req -x509 -newkey rsa:2048 -keyout cert.pem -out cert.crt
  3090. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  3091. // ...
  3092. // -----END ENCRYPTED PRIVATE KEY-----
  3093. // Not encrypted (add -nodes):
  3094. // -----BEGIN PRIVATE KEY-----
  3095. // ...
  3096. // -----END PRIVATE KEY-----
  3097. // Or (openssl genrsa -out client.key 1024 # used for certificate signing request)
  3098. // -----BEGIN RSA PRIVATE KEY-----
  3099. // ...
  3100. // -----END RSA PRIVATE KEY-----
  3101. PrivateKey = PEM_read_PrivateKey(File, NULL, PemPasswordCallback, &CallbackUserData);
  3102. fclose(File);
  3103. try
  3104. {
  3105. if (PrivateKey == NULL)
  3106. {
  3107. ThrowTlsCertificateErrorIgnorePassphraseErrors(Path, HasPassphrase);
  3108. WrongPassphrase = true;
  3109. }
  3110. File = OpenCertificate(Path);
  3111. // The file can contain both private and public key
  3112. // (basically cert.pem and cert.crt appended one to each other)
  3113. // -----BEGIN ENCRYPTED PRIVATE KEY-----
  3114. // ...
  3115. // -----END ENCRYPTED PRIVATE KEY-----
  3116. // -----BEGIN CERTIFICATE-----
  3117. // ...
  3118. // -----END CERTIFICATE-----
  3119. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  3120. fclose(File);
  3121. if (Certificate == NULL)
  3122. {
  3123. int Error = ERR_get_error();
  3124. // unlikely
  3125. if (IsTlsPassphraseError(Error, HasPassphrase))
  3126. {
  3127. WrongPassphrase = true;
  3128. }
  3129. else
  3130. {
  3131. UnicodeString CertificatePath = ChangeFileExt(Path, L".cer");
  3132. if (!FileExists(CertificatePath))
  3133. {
  3134. CertificatePath = ChangeFileExt(Path, L".crt");
  3135. }
  3136. if (!FileExists(CertificatePath))
  3137. {
  3138. throw Exception(MainInstructions(FMTLOAD(CERTIFICATE_PUBLIC_KEY_NOT_FOUND, (Path))));
  3139. }
  3140. else
  3141. {
  3142. File = OpenCertificate(CertificatePath);
  3143. // -----BEGIN CERTIFICATE-----
  3144. // ...
  3145. // -----END CERTIFICATE-----
  3146. Certificate = PEM_read_X509(File, NULL, PemPasswordCallback, &CallbackUserData);
  3147. fclose(File);
  3148. if (Certificate == NULL)
  3149. {
  3150. int Base64Error = ERR_get_error();
  3151. File = OpenCertificate(CertificatePath);
  3152. // Binary DER-encoded certificate
  3153. // (as above, with BEGIN/END removed, and decoded from Base64 to binary)
  3154. // openssl x509 -in cert.crt -out client.der.crt -outform DER
  3155. Certificate = d2i_X509_fp(File, NULL);
  3156. fclose(File);
  3157. if (Certificate == NULL)
  3158. {
  3159. int DERError = ERR_get_error();
  3160. UnicodeString Message = MainInstructions(FMTLOAD(CERTIFICATE_READ_ERROR, (CertificatePath)));
  3161. UnicodeString MoreMessages =
  3162. FORMAT(L"Base64: %s\nDER: %s", (GetTlsErrorStr(Base64Error), GetTlsErrorStr(DERError)));
  3163. throw ExtException(Message, MoreMessages);
  3164. }
  3165. }
  3166. }
  3167. }
  3168. }
  3169. }
  3170. __finally
  3171. {
  3172. // We loaded private key, but failed to load certificate, discard the certificate
  3173. // (either exception was thrown or WrongPassphrase)
  3174. if ((PrivateKey != NULL) && (Certificate == NULL))
  3175. {
  3176. EVP_PKEY_free(PrivateKey);
  3177. PrivateKey = NULL;
  3178. }
  3179. // Certificate was verified, but passphrase was wrong when loading private key,
  3180. // so discard the certificate
  3181. else if ((Certificate != NULL) && (PrivateKey == NULL))
  3182. {
  3183. X509_free(Certificate);
  3184. Certificate = NULL;
  3185. }
  3186. }
  3187. }
  3188. }
  3189. //---------------------------------------------------------------------------
  3190. void __fastcall CheckCertificate(const UnicodeString & Path)
  3191. {
  3192. X509 * Certificate;
  3193. EVP_PKEY * PrivateKey;
  3194. bool WrongPassphrase;
  3195. ParseCertificate(Path, L"", Certificate, PrivateKey, WrongPassphrase);
  3196. if (PrivateKey != NULL)
  3197. {
  3198. EVP_PKEY_free(PrivateKey);
  3199. }
  3200. if (Certificate != NULL)
  3201. {
  3202. X509_free(Certificate);
  3203. }
  3204. }
  3205. //---------------------------------------------------------------------------
  3206. const UnicodeString HttpProtocol(L"http");
  3207. const UnicodeString HttpsProtocol(L"https");
  3208. const UnicodeString ProtocolSeparator(L"://");
  3209. //---------------------------------------------------------------------------
  3210. bool __fastcall IsHttpUrl(const UnicodeString & S)
  3211. {
  3212. return StartsText(HttpProtocol + ProtocolSeparator, S);
  3213. }
  3214. //---------------------------------------------------------------------------
  3215. bool __fastcall IsHttpOrHttpsUrl(const UnicodeString & S)
  3216. {
  3217. return
  3218. IsHttpUrl(S) ||
  3219. StartsText(HttpsProtocol + ProtocolSeparator, S);
  3220. }
  3221. //---------------------------------------------------------------------------
  3222. UnicodeString __fastcall ChangeUrlProtocol(const UnicodeString & S, const UnicodeString & Protocol)
  3223. {
  3224. int P = S.Pos(ProtocolSeparator);
  3225. DebugAssert(P > 0);
  3226. return Protocol + ProtocolSeparator + RightStr(S, S.Length() - P - ProtocolSeparator.Length() + 1);
  3227. }
  3228. //---------------------------------------------------------------------------
  3229. const UnicodeString RtfPara(TraceInitStr(L"\\par\n"));
  3230. const UnicodeString AssemblyNamespace(TraceInitStr(L"WinSCP"));
  3231. const UnicodeString TransferOptionsClassName(TraceInitStr(L"TransferOptions"));
  3232. const UnicodeString SessionClassName(TraceInitStr(L"Session"));
  3233. const UnicodeString RtfHyperlinkField(TraceInitStr(L"HYPERLINK"));
  3234. const UnicodeString RtfHyperlinkFieldPrefix(TraceInitStr(RtfHyperlinkField + L" \""));
  3235. const UnicodeString RtfHyperlinkFieldSuffix(TraceInitStr(L"\" "));
  3236. //---------------------------------------------------------------------
  3237. UnicodeString __fastcall RtfColor(int Index)
  3238. {
  3239. return FORMAT(L"\\cf%d", (Index));
  3240. }
  3241. //---------------------------------------------------------------------
  3242. UnicodeString __fastcall RtfText(const UnicodeString & Text, bool Rtf)
  3243. {
  3244. UnicodeString Result = Text;
  3245. if (Rtf)
  3246. {
  3247. int Index = 1;
  3248. while (Index <= Result.Length())
  3249. {
  3250. UnicodeString Replacement;
  3251. wchar_t Ch = Result[Index];
  3252. if ((Ch == L'\\') || (Ch == L'{') || (Ch == L'}'))
  3253. {
  3254. Replacement = FORMAT(L"\\%s", (Ch));
  3255. }
  3256. else if (Ch >= 0x0080)
  3257. {
  3258. Replacement = FORMAT(L"\\u%d?", (int(Ch)));
  3259. }
  3260. if (!Replacement.IsEmpty())
  3261. {
  3262. Result.Delete(Index, 1);
  3263. Result.Insert(Replacement, Index);
  3264. Index += Replacement.Length();
  3265. }
  3266. else
  3267. {
  3268. Index++;
  3269. }
  3270. }
  3271. }
  3272. return Result;
  3273. }
  3274. //---------------------------------------------------------------------
  3275. UnicodeString __fastcall RtfColorText(int Color, const UnicodeString & Text)
  3276. {
  3277. return RtfColor(Color) + L" " + RtfText(Text) + RtfColor(0) + L" ";
  3278. }
  3279. //---------------------------------------------------------------------
  3280. UnicodeString __fastcall RtfColorItalicText(int Color, const UnicodeString & Text)
  3281. {
  3282. return RtfColor(Color) + L"\\i " + RtfText(Text) + L"\\i0" + RtfColor(0) + L" ";
  3283. }
  3284. //---------------------------------------------------------------------
  3285. UnicodeString __fastcall RtfOverrideColorText(const UnicodeString & Text)
  3286. {
  3287. return RtfColorText(1, Text);
  3288. }
  3289. //---------------------------------------------------------------------
  3290. UnicodeString __fastcall RtfKeyword(const UnicodeString & Text)
  3291. {
  3292. return RtfColorText(5, Text);
  3293. }
  3294. //---------------------------------------------------------------------
  3295. UnicodeString __fastcall RtfParameter(const UnicodeString & Text)
  3296. {
  3297. return RtfColorText(6, Text);
  3298. }
  3299. //---------------------------------------------------------------------
  3300. UnicodeString __fastcall RtfString(const UnicodeString & Text)
  3301. {
  3302. return RtfColorText(4, Text);
  3303. }
  3304. //---------------------------------------------------------------------
  3305. UnicodeString __fastcall RtfLink(const UnicodeString & Link, const UnicodeString & RtfText)
  3306. {
  3307. return
  3308. L"{\\field{\\*\\fldinst{" + RtfHyperlinkFieldPrefix + Link + RtfHyperlinkFieldSuffix + L"}}{\\fldrslt{" +
  3309. RtfText + L"}}}";
  3310. }
  3311. //---------------------------------------------------------------------
  3312. UnicodeString __fastcall ScriptCommandLink(const UnicodeString & Command)
  3313. {
  3314. return L"scriptcommand_" + Command;
  3315. }
  3316. //---------------------------------------------------------------------
  3317. UnicodeString __fastcall RtfSwitch(
  3318. const UnicodeString & Switch, const UnicodeString & Link, bool Rtf)
  3319. {
  3320. UnicodeString Result = FORMAT(L"-%s", (Switch));
  3321. if (Rtf)
  3322. {
  3323. Result = RtfLink(Link + L"#" + Switch.LowerCase(), RtfParameter(Result));
  3324. }
  3325. return L" " + Result;
  3326. }
  3327. //---------------------------------------------------------------------
  3328. UnicodeString __fastcall RtfSwitchValue(
  3329. const UnicodeString & Name, const UnicodeString & Link, const UnicodeString & Value, bool Rtf)
  3330. {
  3331. return RtfSwitch(Name, Link, Rtf) + L"=" + Value;
  3332. }
  3333. //---------------------------------------------------------------------
  3334. UnicodeString __fastcall RtfSwitch(
  3335. const UnicodeString & Name, const UnicodeString & Link, const UnicodeString & Value, bool Rtf)
  3336. {
  3337. return RtfSwitchValue(Name, Link, RtfText(FORMAT("\"%s\"", (EscapeParam(Value))), Rtf), Rtf);
  3338. }
  3339. //---------------------------------------------------------------------
  3340. UnicodeString __fastcall RtfSwitch(
  3341. const UnicodeString & Name, const UnicodeString & Link, int Value, bool Rtf)
  3342. {
  3343. return RtfSwitchValue(Name, Link, RtfText(IntToStr(Value), Rtf), Rtf);
  3344. }
  3345. //---------------------------------------------------------------------
  3346. UnicodeString __fastcall RtfRemoveHyperlinks(UnicodeString Text)
  3347. {
  3348. // Remove all tags HYPERLINK "https://www.example.com".
  3349. // See also RtfEscapeParam
  3350. int Index = 1;
  3351. int P;
  3352. while ((P = PosEx(RtfHyperlinkFieldPrefix, Text, Index)) > 0)
  3353. {
  3354. int Index2 = P + RtfHyperlinkFieldPrefix.Length();
  3355. int P2 = PosEx(RtfHyperlinkFieldSuffix, Text, Index2);
  3356. if (P2 > 0)
  3357. {
  3358. Text.Delete(P, P2 - P + RtfHyperlinkFieldSuffix.Length());
  3359. }
  3360. else
  3361. {
  3362. Index = Index2;
  3363. }
  3364. }
  3365. return Text;
  3366. }
  3367. //---------------------------------------------------------------------
  3368. UnicodeString __fastcall RtfEscapeParam(UnicodeString Param, bool PowerShellEscape)
  3369. {
  3370. const UnicodeString Quote(L"\"");
  3371. UnicodeString Escape(Quote);
  3372. if (PowerShellEscape)
  3373. {
  3374. Escape = "`" + Escape + "`";
  3375. }
  3376. // Equivalent of EscapeParam, except that it does not double quotes in HYPERLINK.
  3377. // See also RtfRemoveHyperlinks.
  3378. int Index = 1;
  3379. while (true)
  3380. {
  3381. int P1 = PosEx(Quote, Param, Index);
  3382. if (P1 == 0)
  3383. {
  3384. // no more quotes
  3385. break;
  3386. }
  3387. else
  3388. {
  3389. int P2 = PosEx(RtfHyperlinkFieldPrefix, Param, Index);
  3390. int P3;
  3391. if ((P2 > 0) && (P2 < P1) && ((P3 = PosEx(RtfHyperlinkFieldSuffix, Param, P2)) > 0))
  3392. {
  3393. // skip HYPERLINK
  3394. Index = P3 + RtfHyperlinkFieldSuffix.Length();
  3395. }
  3396. else
  3397. {
  3398. Param.Insert(Escape, P1);
  3399. Index = P1 + (Escape.Length() + Quote.Length());
  3400. }
  3401. }
  3402. }
  3403. return Param;
  3404. }
  3405. //---------------------------------------------------------------------
  3406. static UnicodeString __fastcall RtfCodeComment(const UnicodeString & Text)
  3407. {
  3408. return RtfColorItalicText(2, Text);
  3409. }
  3410. //---------------------------------------------------------------------
  3411. UnicodeString __fastcall AssemblyCommentLine(TAssemblyLanguage Language, const UnicodeString & Text)
  3412. {
  3413. UnicodeString Prefix;
  3414. switch (Language)
  3415. {
  3416. case alCSharp:
  3417. Prefix = L"//";
  3418. break;
  3419. case alVBNET:
  3420. Prefix = L"'";
  3421. break;
  3422. case alPowerShell:
  3423. Prefix = L"#";
  3424. break;
  3425. }
  3426. return RtfCodeComment(Prefix + L" " + Text) + RtfPara;
  3427. }
  3428. //---------------------------------------------------------------------
  3429. UnicodeString __fastcall AssemblyString(TAssemblyLanguage Language, UnicodeString S)
  3430. {
  3431. switch (Language)
  3432. {
  3433. case alCSharp:
  3434. if (S.Pos(L"\\") > 0)
  3435. {
  3436. S = FORMAT(L"@\"%s\"", (ReplaceStr(S, L"\"", L"\"\"")));
  3437. }
  3438. else
  3439. {
  3440. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"\\\"")));
  3441. }
  3442. break;
  3443. case alVBNET:
  3444. S = FORMAT(L"\"%s\"", (ReplaceStr(S, L"\"", L"\"\"")));
  3445. break;
  3446. case alPowerShell:
  3447. S = FORMAT(L"\"%s\"", (ReplaceStr(ReplaceStr(ReplaceStr(S, L"`", L"``"), L"$", L"`$"), L"\"", L"`\"")));
  3448. break;
  3449. default:
  3450. DebugFail();
  3451. break;
  3452. }
  3453. return RtfString(S);
  3454. }
  3455. //---------------------------------------------------------------------
  3456. static UnicodeString __fastcall RtfClass(const UnicodeString & Text)
  3457. {
  3458. return RtfColorText(3, Text);
  3459. }
  3460. //---------------------------------------------------------------------
  3461. UnicodeString __fastcall RtfLibraryClass(const UnicodeString & ClassName)
  3462. {
  3463. return RtfLink(L"library_" + ClassName.LowerCase(), RtfClass(ClassName));
  3464. }
  3465. //---------------------------------------------------------------------
  3466. UnicodeString __fastcall RtfLibraryMethod(const UnicodeString & ClassName, const UnicodeString & MethodName, bool InPage)
  3467. {
  3468. return RtfLink(L"library_" + ClassName.LowerCase() + (InPage ? L"#" : L"_") + MethodName.LowerCase(), RtfOverrideColorText(MethodName));
  3469. }
  3470. //---------------------------------------------------------------------
  3471. static UnicodeString __fastcall RtfLibraryProperty(const UnicodeString & ClassName, const UnicodeString & PropertyName)
  3472. {
  3473. return RtfLink(L"library_" + ClassName.LowerCase() + L"#" + PropertyName.LowerCase(), RtfOverrideColorText(PropertyName));
  3474. }
  3475. //---------------------------------------------------------------------
  3476. UnicodeString __fastcall AssemblyVariableName(TAssemblyLanguage Language, const UnicodeString & ClassName)
  3477. {
  3478. UnicodeString Result = ClassName.SubString(1, 1).LowerCase() + ClassName.SubString(2, ClassName.Length() - 1);
  3479. if (Language == alPowerShell)
  3480. {
  3481. Result = L"$" + Result;
  3482. }
  3483. return Result;
  3484. }
  3485. //---------------------------------------------------------------------
  3486. UnicodeString __fastcall AssemblyStatementSeparator(TAssemblyLanguage Language)
  3487. {
  3488. UnicodeString Result;
  3489. switch (Language)
  3490. {
  3491. case alCSharp:
  3492. Result = L";";
  3493. break;
  3494. case alVBNET:
  3495. case alPowerShell:
  3496. // noop
  3497. break;
  3498. }
  3499. return Result;
  3500. }
  3501. //---------------------------------------------------------------------
  3502. UnicodeString __fastcall AssemblyPropertyRaw(
  3503. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name,
  3504. const UnicodeString & Value, bool Inline)
  3505. {
  3506. UnicodeString Result;
  3507. UnicodeString RtfPropertyAndValue = RtfLibraryProperty(ClassName, Name) + L" = " + Value;
  3508. UnicodeString Indetation = (Inline ? L"" : L" ");
  3509. UnicodeString SpaceOrPara = (Inline ? UnicodeString(L" ") : RtfPara);
  3510. switch (Language)
  3511. {
  3512. case alCSharp:
  3513. Result = Indetation + RtfPropertyAndValue + (Inline ? L"" : L",") + SpaceOrPara;
  3514. break;
  3515. case alVBNET:
  3516. Result = Indetation + L"." + RtfPropertyAndValue + SpaceOrPara;
  3517. break;
  3518. case alPowerShell:
  3519. Result = Indetation + RtfPropertyAndValue + SpaceOrPara;
  3520. break;
  3521. }
  3522. return Result;
  3523. }
  3524. //---------------------------------------------------------------------
  3525. UnicodeString __fastcall AssemblyProperty(
  3526. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name,
  3527. const UnicodeString & Type, const UnicodeString & Member, bool Inline)
  3528. {
  3529. UnicodeString PropertyValue;
  3530. switch (Language)
  3531. {
  3532. case alCSharp:
  3533. case alVBNET:
  3534. PropertyValue = RtfClass(Type) + RtfText(L"." + Member);
  3535. break;
  3536. case alPowerShell:
  3537. PropertyValue = RtfText(L"[" + AssemblyNamespace + L".") + RtfClass(Type) + RtfText(L"]::" + Member);
  3538. break;
  3539. }
  3540. return AssemblyPropertyRaw(Language, ClassName, Name, PropertyValue, Inline);
  3541. }
  3542. //---------------------------------------------------------------------
  3543. UnicodeString __fastcall AssemblyProperty(
  3544. TAssemblyLanguage Language, const UnicodeString & ClassName,
  3545. const UnicodeString & Name, const UnicodeString & Value, bool Inline)
  3546. {
  3547. return AssemblyPropertyRaw(Language, ClassName, Name, AssemblyString(Language, Value), Inline);
  3548. }
  3549. //---------------------------------------------------------------------
  3550. UnicodeString __fastcall AssemblyProperty(
  3551. TAssemblyLanguage Language, const UnicodeString & ClassName,
  3552. const UnicodeString & Name, int Value, bool Inline)
  3553. {
  3554. return AssemblyPropertyRaw(Language, ClassName, Name, IntToStr(Value), Inline);
  3555. }
  3556. //---------------------------------------------------------------------
  3557. UnicodeString __fastcall AssemblyBoolean(TAssemblyLanguage Language, bool Value)
  3558. {
  3559. UnicodeString Result;
  3560. switch (Language)
  3561. {
  3562. case alCSharp:
  3563. Result = (Value ? L"true" : L"false");
  3564. break;
  3565. case alVBNET:
  3566. Result = (Value ? L"True" : L"False");
  3567. break;
  3568. case alPowerShell:
  3569. Result = (Value ? L"$True" : L"$False");
  3570. break;
  3571. }
  3572. return Result;
  3573. }
  3574. //---------------------------------------------------------------------
  3575. UnicodeString __fastcall AssemblyProperty(
  3576. TAssemblyLanguage Language, const UnicodeString & ClassName, const UnicodeString & Name, bool Value, bool Inline)
  3577. {
  3578. UnicodeString PropertyValue = AssemblyBoolean(Language, Value);
  3579. return AssemblyPropertyRaw(Language, ClassName, Name, PropertyValue, Inline);
  3580. }
  3581. //---------------------------------------------------------------------
  3582. UnicodeString __fastcall AssemblyNewClassInstance(TAssemblyLanguage Language, const UnicodeString & ClassName, bool Inline)
  3583. {
  3584. UnicodeString VariableName = AssemblyVariableName(Language, ClassName);
  3585. UnicodeString RtfClass = RtfLibraryClass(ClassName);
  3586. UnicodeString Result;
  3587. switch (Language)
  3588. {
  3589. case alCSharp:
  3590. if (!Inline)
  3591. {
  3592. Result += RtfClass + RtfText(L" " + VariableName + L" = ");
  3593. }
  3594. Result += RtfKeyword(L"new") + RtfText(L" ") + RtfClass;
  3595. break;
  3596. case alVBNET:
  3597. if (!Inline)
  3598. {
  3599. Result += RtfText(VariableName + L" ") + RtfKeyword(L"As") + RtfText(L" ");
  3600. }
  3601. Result += RtfKeyword(L"New") + RtfText(" ") + RtfClass;
  3602. break;
  3603. case alPowerShell:
  3604. if (!Inline)
  3605. {
  3606. Result += RtfText(VariableName + L" = ");
  3607. }
  3608. Result += RtfKeyword(L"New-Object") + RtfText(L" " + AssemblyNamespace + L".") + RtfClass;
  3609. break;
  3610. }
  3611. return Result;
  3612. }
  3613. //---------------------------------------------------------------------
  3614. UnicodeString __fastcall AssemblyVariableDeclaration(TAssemblyLanguage Language)
  3615. {
  3616. UnicodeString Result;
  3617. switch (Language)
  3618. {
  3619. case alVBNET:
  3620. Result = RtfKeyword(L"Dim") + RtfText(L" ");
  3621. break;
  3622. }
  3623. return Result;
  3624. }
  3625. //---------------------------------------------------------------------
  3626. UnicodeString __fastcall AssemblyNewClassInstanceStart(
  3627. TAssemblyLanguage Language, const UnicodeString & ClassName, bool Inline)
  3628. {
  3629. UnicodeString SpaceOrPara = (Inline ? UnicodeString(L" ") : RtfPara);
  3630. UnicodeString Result;
  3631. if (!Inline)
  3632. {
  3633. Result += AssemblyVariableDeclaration(Language);
  3634. }
  3635. Result += AssemblyNewClassInstance(Language, ClassName, Inline);
  3636. switch (Language)
  3637. {
  3638. case alCSharp:
  3639. Result += SpaceOrPara + RtfText(L"{") + SpaceOrPara;
  3640. break;
  3641. case alVBNET:
  3642. // Historically we use Dim .. With instead of object initilizer.
  3643. // But for inline use, we have to use object initialize.
  3644. // We should consistently always use object initilizers.
  3645. // Unfortunatelly VB.NET object initializer (contrary to C#) does not allow trailing comma.
  3646. Result += SpaceOrPara + RtfKeyword(L"With");
  3647. if (Inline)
  3648. {
  3649. Result += RtfText(L" { ");
  3650. }
  3651. else
  3652. {
  3653. Result += RtfText(L" " + AssemblyVariableName(Language, ClassName)) + RtfPara;
  3654. }
  3655. break;
  3656. case alPowerShell:
  3657. Result += RtfText(" -Property @{") + SpaceOrPara;
  3658. break;
  3659. }
  3660. return Result;
  3661. }
  3662. //---------------------------------------------------------------------
  3663. UnicodeString __fastcall AssemblyNewClassInstanceEnd(TAssemblyLanguage Language, bool Inline)
  3664. {
  3665. UnicodeString InlineEnd = RtfText(L"}");
  3666. UnicodeString Result;
  3667. switch (Language)
  3668. {
  3669. case alCSharp:
  3670. if (Inline)
  3671. {
  3672. Result = InlineEnd;
  3673. }
  3674. else
  3675. {
  3676. Result = RtfText(L"};") + RtfPara;
  3677. }
  3678. break;
  3679. case alVBNET:
  3680. if (Inline)
  3681. {
  3682. Result = InlineEnd;
  3683. }
  3684. else
  3685. {
  3686. Result = RtfKeyword(L"End With") + RtfPara;
  3687. }
  3688. break;
  3689. case alPowerShell:
  3690. if (Inline)
  3691. {
  3692. Result = InlineEnd;
  3693. }
  3694. else
  3695. {
  3696. Result = RtfText(L"}") + RtfPara;
  3697. }
  3698. break;
  3699. }
  3700. return Result;
  3701. }
  3702. //---------------------------------------------------------------------------
  3703. UnicodeString __fastcall AssemblyAddRawSettings(
  3704. TAssemblyLanguage Language, TStrings * RawSettings, const UnicodeString & ClassName,
  3705. const UnicodeString & MethodName)
  3706. {
  3707. UnicodeString Result;
  3708. for (int Index = 0; Index < RawSettings->Count; Index++)
  3709. {
  3710. UnicodeString Name = RawSettings->Names[Index];
  3711. UnicodeString Value = RawSettings->ValueFromIndex[Index];
  3712. UnicodeString AddRawSettingsMethod =
  3713. RtfLibraryMethod(ClassName, MethodName, false) +
  3714. FORMAT(L"(%s, %s)", (AssemblyString(Language, Name), AssemblyString(Language, Value)));
  3715. UnicodeString VariableName = AssemblyVariableName(Language, ClassName);
  3716. Result += RtfText(VariableName + L".") + AddRawSettingsMethod + AssemblyStatementSeparator(Language) + RtfPara;
  3717. }
  3718. return Result;
  3719. }
  3720. //---------------------------------------------------------------------------
  3721. void __fastcall LoadScriptFromFile(UnicodeString FileName, TStrings * Lines)
  3722. {
  3723. std::auto_ptr<TFileStream> Stream(new TFileStream(ApiPath(FileName), fmOpenRead | fmShareDenyWrite));
  3724. Lines->DefaultEncoding = TEncoding::UTF8;
  3725. try
  3726. {
  3727. Lines->LoadFromStream(Stream.get());
  3728. }
  3729. catch (EEncodingError & E)
  3730. {
  3731. throw ExtException(LoadStr(TEXT_FILE_ENCODING), &E);
  3732. }
  3733. }
  3734. //---------------------------------------------------------------------------
  3735. UnicodeString __fastcall StripEllipsis(const UnicodeString & S)
  3736. {
  3737. UnicodeString Result = S;
  3738. if (Result.SubString(Result.Length() - Ellipsis.Length() + 1, Ellipsis.Length()) == Ellipsis)
  3739. {
  3740. Result.SetLength(Result.Length() - Ellipsis.Length());
  3741. Result = Result.TrimRight();
  3742. }
  3743. return Result;
  3744. }
  3745. //---------------------------------------------------------------------------
  3746. UnicodeString __fastcall GetFileMimeType(const UnicodeString & FileName)
  3747. {
  3748. wchar_t * MimeOut = NULL;
  3749. UnicodeString Result;
  3750. if (FindMimeFromData(NULL, FileName.c_str(), NULL, 0, NULL, FMFD_URLASFILENAME, &MimeOut, 0) == S_OK)
  3751. {
  3752. Result = MimeOut;
  3753. CoTaskMemFree(MimeOut);
  3754. }
  3755. return Result;
  3756. }
  3757. //---------------------------------------------------------------------------
  3758. UnicodeString NormalizeString(const UnicodeString & S)
  3759. {
  3760. UnicodeString Result = S;
  3761. if (Result == EmptyString)
  3762. {
  3763. Result = UnicodeString();
  3764. }
  3765. return Result;
  3766. }
  3767. //---------------------------------------------------------------------------
  3768. TStrings * TlsCipherList()
  3769. {
  3770. // OpenSSL initialization happens in NeonInitialize
  3771. std::unique_ptr<TStrings> Result(new TStringList());
  3772. const SSL_METHOD * Method = DTLS_client_method();
  3773. SSL_CTX * Ctx = SSL_CTX_new(Method);
  3774. SSL * Ssl = SSL_new(Ctx);
  3775. int Index = 0;
  3776. const char * CipherName;
  3777. do
  3778. {
  3779. CipherName = SSL_get_cipher_list(Ssl, Index);
  3780. Index++;
  3781. if (CipherName != NULL)
  3782. {
  3783. Result->Add(UnicodeString(CipherName));
  3784. }
  3785. }
  3786. while (CipherName != NULL);
  3787. return Result.release();
  3788. }