Common.cpp 125 KB

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