Common.cpp 127 KB

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