Common.cpp 121 KB

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