Common.cpp 128 KB

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