Common.cpp 125 KB

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