Common.cpp 127 KB

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