Common.cpp 129 KB

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