https.cpp 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900
  1. #include "https.h"
  2. #include "details.h"
  3. #include "factory.h"
  4. #include "http_common.h"
  5. #include "jobqueue.h"
  6. #include "location.h"
  7. #include "multi.h"
  8. #include "pipequeue.h"
  9. #include "utils.h"
  10. #include <openssl/ssl.h>
  11. #include <openssl/err.h>
  12. #include <openssl/bio.h>
  13. #include <openssl/x509v3.h>
  14. #include <library/cpp/openssl/init/init.h>
  15. #include <library/cpp/openssl/method/io.h>
  16. #include <library/cpp/coroutine/listener/listen.h>
  17. #include <library/cpp/dns/cache.h>
  18. #include <library/cpp/http/misc/parsed_request.h>
  19. #include <library/cpp/http/misc/httpcodes.h>
  20. #include <library/cpp/http/io/stream.h>
  21. #include <util/generic/cast.h>
  22. #include <util/generic/list.h>
  23. #include <util/generic/utility.h>
  24. #include <util/network/socket.h>
  25. #include <util/stream/str.h>
  26. #include <util/stream/zlib.h>
  27. #include <util/string/builder.h>
  28. #include <util/string/cast.h>
  29. #include <util/system/condvar.h>
  30. #include <util/system/error.h>
  31. #include <util/system/types.h>
  32. #include <util/thread/factory.h>
  33. #include <atomic>
  34. #if defined(_unix_)
  35. #include <sys/ioctl.h>
  36. #endif
  37. #if defined(_linux_)
  38. #undef SIOCGSTAMP
  39. #undef SIOCGSTAMPNS
  40. #include <linux/sockios.h>
  41. #define FIONWRITE SIOCOUTQ
  42. #endif
  43. using namespace NDns;
  44. using namespace NAddr;
  45. namespace NNeh {
  46. TString THttpsOptions::CAFile;
  47. TString THttpsOptions::CAPath;
  48. TString THttpsOptions::ClientCertificate;
  49. TString THttpsOptions::ClientPrivateKey;
  50. TString THttpsOptions::ClientPrivateKeyPassword;
  51. bool THttpsOptions::EnableSslServerDebug = false;
  52. bool THttpsOptions::EnableSslClientDebug = false;
  53. bool THttpsOptions::CheckCertificateHostname = false;
  54. THttpsOptions::TVerifyCallback THttpsOptions::ClientVerifyCallback = nullptr;
  55. THttpsOptions::TPasswordCallback THttpsOptions::KeyPasswdCallback = nullptr;
  56. bool THttpsOptions::RedirectionNotError = false;
  57. bool THttpsOptions::Set(TStringBuf name, TStringBuf value) {
  58. #define YNDX_NEH_HTTPS_TRY_SET(optName) \
  59. if (name == TStringBuf(#optName)) { \
  60. optName = FromString<decltype(optName)>(value); \
  61. return true; \
  62. }
  63. YNDX_NEH_HTTPS_TRY_SET(CAFile);
  64. YNDX_NEH_HTTPS_TRY_SET(CAPath);
  65. YNDX_NEH_HTTPS_TRY_SET(ClientCertificate);
  66. YNDX_NEH_HTTPS_TRY_SET(ClientPrivateKey);
  67. YNDX_NEH_HTTPS_TRY_SET(ClientPrivateKeyPassword);
  68. YNDX_NEH_HTTPS_TRY_SET(EnableSslServerDebug);
  69. YNDX_NEH_HTTPS_TRY_SET(EnableSslClientDebug);
  70. YNDX_NEH_HTTPS_TRY_SET(CheckCertificateHostname);
  71. YNDX_NEH_HTTPS_TRY_SET(RedirectionNotError);
  72. #undef YNDX_NEH_HTTPS_TRY_SET
  73. return false;
  74. }
  75. }
  76. namespace NNeh {
  77. namespace NHttps {
  78. namespace {
  79. // force ssl_write/ssl_read functions to return this value via BIO_method_read/write that means request is canceled
  80. constexpr int SSL_RVAL_TIMEOUT = -42;
  81. struct TInputConnections {
  82. TInputConnections()
  83. : Counter(0)
  84. , MaxUnusedConnKeepaliveTimeout(120)
  85. , MinUnusedConnKeepaliveTimeout(10)
  86. {
  87. }
  88. inline size_t ExceedSoftLimit() const noexcept {
  89. return NHttp::TFdLimits::ExceedLimit(Counter.Val(), Limits.Soft());
  90. }
  91. inline size_t ExceedHardLimit() const noexcept {
  92. return NHttp::TFdLimits::ExceedLimit(Counter.Val(), Limits.Hard());
  93. }
  94. inline size_t DeltaLimit() const noexcept {
  95. return Limits.Delta();
  96. }
  97. unsigned UnusedConnKeepaliveTimeout() const {
  98. if (size_t e = ExceedSoftLimit()) {
  99. size_t d = DeltaLimit();
  100. size_t leftAvailableFd = NHttp::TFdLimits::ExceedLimit(d, e);
  101. unsigned r = static_cast<unsigned>(MaxUnusedConnKeepaliveTimeout.load(std::memory_order_acquire) * leftAvailableFd / (d + 1));
  102. return Max(r, (unsigned)MinUnusedConnKeepaliveTimeout.load(std::memory_order_acquire));
  103. }
  104. return MaxUnusedConnKeepaliveTimeout.load(std::memory_order_acquire);
  105. }
  106. void SetFdLimits(size_t soft, size_t hard) {
  107. Limits.SetSoft(soft);
  108. Limits.SetHard(hard);
  109. }
  110. NHttp::TFdLimits Limits;
  111. TAtomicCounter Counter;
  112. std::atomic<unsigned> MaxUnusedConnKeepaliveTimeout; //in seconds
  113. std::atomic<unsigned> MinUnusedConnKeepaliveTimeout; //in seconds
  114. };
  115. TInputConnections* InputConnections() {
  116. return Singleton<TInputConnections>();
  117. }
  118. struct TSharedSocket: public TSocketHolder, public TAtomicRefCount<TSharedSocket> {
  119. inline TSharedSocket(TSocketHolder& s)
  120. : TSocketHolder(s.Release())
  121. {
  122. InputConnections()->Counter.Inc();
  123. }
  124. ~TSharedSocket() {
  125. InputConnections()->Counter.Dec();
  126. }
  127. };
  128. using TSocketRef = TIntrusivePtr<TSharedSocket>;
  129. struct TX509Deleter {
  130. static void Destroy(X509* cert) {
  131. X509_free(cert);
  132. }
  133. };
  134. using TX509Holder = THolder<X509, TX509Deleter>;
  135. struct TSslSessionDeleter {
  136. static void Destroy(SSL_SESSION* sess) {
  137. SSL_SESSION_free(sess);
  138. }
  139. };
  140. using TSslSessionHolder = THolder<SSL_SESSION, TSslSessionDeleter>;
  141. struct TSslDeleter {
  142. static void Destroy(SSL* ssl) {
  143. SSL_free(ssl);
  144. }
  145. };
  146. using TSslHolder = THolder<SSL, TSslDeleter>;
  147. // read from bio and write via operator<<() to dst
  148. template <typename T>
  149. class TBIOInput : public NOpenSSL::TAbstractIO {
  150. public:
  151. TBIOInput(T& dst)
  152. : Dst_(dst)
  153. {
  154. }
  155. int Write(const char* data, size_t dlen, size_t* written) override {
  156. Dst_ << TStringBuf(data, dlen);
  157. *written = dlen;
  158. return 1;
  159. }
  160. int Read(char* data, size_t dlen, size_t* readbytes) override {
  161. Y_UNUSED(data);
  162. Y_UNUSED(dlen);
  163. Y_UNUSED(readbytes);
  164. return -1;
  165. }
  166. int Puts(const char* buf) override {
  167. Y_UNUSED(buf);
  168. return -1;
  169. }
  170. int Gets(char* buf, int len) override {
  171. Y_UNUSED(buf);
  172. Y_UNUSED(len);
  173. return -1;
  174. }
  175. void Flush() override {
  176. }
  177. private:
  178. T& Dst_;
  179. };
  180. }
  181. class TSslException: public yexception {
  182. public:
  183. TSslException() = default;
  184. TSslException(TStringBuf f) {
  185. *this << f << Endl;
  186. InitErr();
  187. }
  188. TSslException(TStringBuf f, const SSL* ssl, int ret) {
  189. *this << f << TStringBuf(" error type: ");
  190. const int etype = SSL_get_error(ssl, ret);
  191. switch (etype) {
  192. case SSL_ERROR_ZERO_RETURN:
  193. *this << TStringBuf("SSL_ERROR_ZERO_RETURN");
  194. break;
  195. case SSL_ERROR_WANT_READ:
  196. *this << TStringBuf("SSL_ERROR_WANT_READ");
  197. break;
  198. case SSL_ERROR_WANT_WRITE:
  199. *this << TStringBuf("SSL_ERROR_WANT_WRITE");
  200. break;
  201. case SSL_ERROR_WANT_CONNECT:
  202. *this << TStringBuf("SSL_ERROR_WANT_CONNECT");
  203. break;
  204. case SSL_ERROR_WANT_ACCEPT:
  205. *this << TStringBuf("SSL_ERROR_WANT_ACCEPT");
  206. break;
  207. case SSL_ERROR_WANT_X509_LOOKUP:
  208. *this << TStringBuf("SSL_ERROR_WANT_X509_LOOKUP");
  209. break;
  210. case SSL_ERROR_SYSCALL:
  211. *this << TStringBuf("SSL_ERROR_SYSCALL ret: ") << ret << TStringBuf(", errno: ") << errno;
  212. break;
  213. case SSL_ERROR_SSL:
  214. *this << TStringBuf("SSL_ERROR_SSL");
  215. break;
  216. }
  217. *this << ' ';
  218. InitErr();
  219. }
  220. private:
  221. void InitErr() {
  222. TBIOInput<TSslException> bio(*this);
  223. ERR_print_errors(bio);
  224. }
  225. };
  226. namespace {
  227. enum EMatchResult {
  228. MATCH_FOUND,
  229. NO_MATCH,
  230. NO_EXTENSION,
  231. ERROR
  232. };
  233. bool EqualNoCase(TStringBuf a, TStringBuf b) {
  234. return (a.size() == b.size()) && ToString(a).to_lower() == ToString(b).to_lower();
  235. }
  236. bool MatchDomainName(TStringBuf tmpl, TStringBuf name) {
  237. // match wildcards only in the left-most part
  238. // do not support (optional according to RFC) partial wildcards (ww*.yandex.ru)
  239. // see RFC-6125
  240. TStringBuf tmplRest = tmpl;
  241. TStringBuf tmplFirst = tmplRest.NextTok('.');
  242. if (tmplFirst == "*") {
  243. tmpl = tmplRest;
  244. name.NextTok('.');
  245. }
  246. return EqualNoCase(tmpl, name);
  247. }
  248. EMatchResult MatchCertAltNames(X509* cert, TStringBuf hostname) {
  249. EMatchResult result = NO_MATCH;
  250. STACK_OF(GENERAL_NAME)* names = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(cert, NID_subject_alt_name, nullptr, NULL);
  251. if (!names) {
  252. return NO_EXTENSION;
  253. }
  254. int namesCt = sk_GENERAL_NAME_num(names);
  255. for (int i = 0; i < namesCt; ++i) {
  256. const GENERAL_NAME* name = sk_GENERAL_NAME_value(names, i);
  257. if (name->type == GEN_DNS) {
  258. TStringBuf dnsName((const char*)ASN1_STRING_get0_data(name->d.dNSName), ASN1_STRING_length(name->d.dNSName));
  259. if (MatchDomainName(dnsName, hostname)) {
  260. result = MATCH_FOUND;
  261. break;
  262. }
  263. }
  264. }
  265. sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
  266. return result;
  267. }
  268. EMatchResult MatchCertCommonName(X509* cert, TStringBuf hostname) {
  269. int commonNameLoc = X509_NAME_get_index_by_NID(X509_get_subject_name(cert), NID_commonName, -1);
  270. if (commonNameLoc < 0) {
  271. return ERROR;
  272. }
  273. X509_NAME_ENTRY* commonNameEntry = X509_NAME_get_entry(X509_get_subject_name(cert), commonNameLoc);
  274. if (!commonNameEntry) {
  275. return ERROR;
  276. }
  277. ASN1_STRING* commonNameAsn1 = X509_NAME_ENTRY_get_data(commonNameEntry);
  278. if (!commonNameAsn1) {
  279. return ERROR;
  280. }
  281. TStringBuf commonName((const char*)ASN1_STRING_get0_data(commonNameAsn1), ASN1_STRING_length(commonNameAsn1));
  282. return MatchDomainName(commonName, hostname)
  283. ? MATCH_FOUND
  284. : NO_MATCH;
  285. }
  286. bool CheckCertHostname(X509* cert, TStringBuf hostname) {
  287. switch (MatchCertAltNames(cert, hostname)) {
  288. case MATCH_FOUND:
  289. return true;
  290. break;
  291. case NO_EXTENSION:
  292. return MatchCertCommonName(cert, hostname) == MATCH_FOUND;
  293. break;
  294. default:
  295. return false;
  296. }
  297. }
  298. void ParseUserInfo(const TParsedLocation& loc, TString& cert, TString& pvtKey) {
  299. if (!loc.UserInfo) {
  300. return;
  301. }
  302. TStringBuf kws = loc.UserInfo;
  303. while (kws) {
  304. TStringBuf name = kws.NextTok('=');
  305. TStringBuf value = kws.NextTok(';');
  306. if (TStringBuf("cert") == name) {
  307. cert = value;
  308. } else if (TStringBuf("key") == name) {
  309. pvtKey = value;
  310. }
  311. }
  312. }
  313. struct TSSLInit {
  314. inline TSSLInit() {
  315. InitOpenSSL();
  316. }
  317. } SSL_INIT;
  318. }
  319. static inline void PrepareSocket(SOCKET s) {
  320. SetNoDelay(s, true);
  321. }
  322. class TConnCache;
  323. static TConnCache* ConnectionCache();
  324. class TConnCache: public IThreadFactory::IThreadAble {
  325. public:
  326. struct TConnection;
  327. typedef TAutoPtr<TSocketHolder> TSocketRef;
  328. typedef THolder<TConnection> TConnectionHolder;
  329. typedef TAutoPtr<TConnectionHolder> TConnectionRef;
  330. typedef TAutoLockFreeQueue<TConnectionHolder> TConnList;
  331. struct TConnection {
  332. inline TConnection(TSocketRef& s, const TResolvedHost host) noexcept
  333. : Socket(s)
  334. , Host(host)
  335. {
  336. ConnectionCache()->ActiveConnections.Inc();
  337. }
  338. inline ~TConnection() {
  339. if (!!Socket && IsNotSocketClosedByOtherSide(*Socket)) {
  340. if (!!Ssl) {
  341. ResetBIO();
  342. // do not wait for shutdown confirmation
  343. Y_UNUSED(SSL_shutdown(Ssl.Get()));
  344. }
  345. }
  346. ConnectionCache()->ActiveConnections.Dec();
  347. }
  348. void ResetBIO() {
  349. if (!!Socket) {
  350. BIO* bio = BIO_new_socket(*Socket, 0);
  351. SSL_set_bio(Ssl.Get(), bio, bio);
  352. }
  353. }
  354. bool HasSsl() const {
  355. return Ssl.Get();
  356. }
  357. TSslHolder&& MoveSsl() {
  358. return std::move(Ssl);
  359. }
  360. void SetSsl(TSslHolder&& ssl) {
  361. Ssl = std::move(ssl);
  362. }
  363. bool ShutdownReceived() {
  364. if (!Ssl) {
  365. return false;
  366. }
  367. char buffer;
  368. int rval = SSL_peek(Ssl.Get(), &buffer, sizeof(buffer));
  369. if (rval) {
  370. return false;
  371. }
  372. return (SSL_get_shutdown(Ssl.Get()) & SSL_RECEIVED_SHUTDOWN);
  373. }
  374. SOCKET Fd() {
  375. return *Socket;
  376. }
  377. protected:
  378. friend class TConnCache;
  379. TSslHolder Ssl;
  380. TSocketRef Socket;
  381. public:
  382. const TResolvedHost Host;
  383. };
  384. TConnCache()
  385. : InPurging_(0)
  386. , MaxConnId_(0)
  387. , Shutdown_(false)
  388. {
  389. T_ = SystemThreadFactory()->Run(this);
  390. }
  391. ~TConnCache() override {
  392. {
  393. TGuard<TMutex> g(PurgeMutex_);
  394. Shutdown_ = true;
  395. CondPurge_.Signal();
  396. }
  397. T_->Join();
  398. }
  399. TConnectionRef Connect(TCont* c, const TString& msgAddr, const TResolvedHost& addr, TErrorRef* error) {
  400. if (ExceedHardLimit()) {
  401. if (error) {
  402. *error = new TError("neh::https output connections limit reached", TError::TType::UnknownType);
  403. }
  404. return nullptr;
  405. }
  406. TConnectionRef res;
  407. TConnList& connList = ConnList(addr);
  408. while (connList.Dequeue(&res)) {
  409. ActiveConnections.Inc();
  410. CachedConnections.Dec();
  411. if (IsNotSocketClosedByOtherSide((*res)->Fd()) && !(*res)->ShutdownReceived()) {
  412. return res;
  413. }
  414. }
  415. if (!c) {
  416. if (error) {
  417. *error = new TError("directo connection failed");
  418. }
  419. return nullptr;
  420. }
  421. const TInstant now(TInstant::Now());
  422. const TInstant deadline(now + TDuration::Seconds(10));
  423. TDuration delay = TDuration::MilliSeconds(8);
  424. TInstant checkpoint = Min(deadline, delay.ToDeadLine());
  425. TNetworkAddress::TIterator ait = addr.Addr.Begin();
  426. TSocketRef socket(new TSocketHolder(NCoro::Socket(*ait)));
  427. int ret = NCoro::ConnectD(c, *socket, *ait, deadline);
  428. res.Reset(new TConnectionHolder);
  429. res->Reset(new TConnection(socket, addr));
  430. if (ret) {
  431. do {
  432. if ((ret == ETIMEDOUT || ret == EINTR) && checkpoint < deadline) {
  433. delay += delay;
  434. checkpoint = Min(deadline, now + delay);
  435. TConnectionRef res2;
  436. if (connList.Dequeue(&res2)) {
  437. ActiveConnections.Inc();
  438. CachedConnections.Dec();
  439. if (IsNotSocketClosedByOtherSide((*res2)->Fd()) && !(*res)->ShutdownReceived()) {
  440. return res2;
  441. }
  442. }
  443. } else {
  444. if (error) {
  445. *error = new TError(TStringBuilder() << TStringBuf("can not connect to ") << msgAddr);
  446. }
  447. return nullptr;
  448. }
  449. } while (ret = NCoro::PollD(c, (*res)->Fd(), CONT_POLL_WRITE, checkpoint));
  450. }
  451. PrepareSocket((*res)->Fd());
  452. return res;
  453. }
  454. inline void Release(TConnectionRef conn) {
  455. if (!ExceedHardLimit()) {
  456. size_t maxConnId = MaxConnId_.load(std::memory_order_acquire);
  457. while (maxConnId < (*conn)->Host.Id) {
  458. MaxConnId_.compare_exchange_strong(
  459. maxConnId,
  460. (*conn)->Host.Id,
  461. std::memory_order_seq_cst,
  462. std::memory_order_seq_cst);
  463. maxConnId = MaxConnId_.load(std::memory_order_acquire);
  464. }
  465. ConnList((*conn)->Host).Enqueue(conn);
  466. CachedConnections.Inc();
  467. ActiveConnections.Dec();
  468. }
  469. if (CachedConnections.Val() && ExceedSoftLimit()) {
  470. SuggestPurgeCache();
  471. }
  472. }
  473. void SetFdLimits(size_t soft, size_t hard) {
  474. Limits.SetSoft(soft);
  475. Limits.SetHard(hard);
  476. }
  477. private:
  478. void SuggestPurgeCache() {
  479. if (AtomicTryLock(&InPurging_)) {
  480. //evaluate the usefulness of purging the cache
  481. //если в кеше мало соединений (< MaxConnId_/16 или 64), не чистим кеш
  482. if ((size_t)CachedConnections.Val() > (Min((size_t)MaxConnId_.load(std::memory_order_acquire), (size_t)1024U) >> 4)) {
  483. //по мере приближения к hardlimit нужда в чистке cache приближается к 100%
  484. size_t closenessToHardLimit256 = ((ActiveConnections.Val() + 1) << 8) / (Limits.Delta() + 1);
  485. //чем больше соединений в кеше, а не в работе, тем менее нужен кеш (можно его почистить)
  486. size_t cacheUselessness256 = ((CachedConnections.Val() + 1) << 8) / (ActiveConnections.Val() + 1);
  487. //итого, - пороги срабатывания:
  488. //при достижении soft-limit, если соединения в кеше, а не в работе
  489. //на полпути от soft-limit к hard-limit, если в кеше больше половины соединений
  490. //при приближении к hardlimit пытаться почистить кеш почти постоянно
  491. if ((closenessToHardLimit256 + cacheUselessness256) >= 256U) {
  492. TGuard<TMutex> g(PurgeMutex_);
  493. CondPurge_.Signal();
  494. return; //memo: thread MUST unlock InPurging_ (see DoExecute())
  495. }
  496. }
  497. AtomicUnlock(&InPurging_);
  498. }
  499. }
  500. void DoExecute() override {
  501. while (true) {
  502. {
  503. TGuard<TMutex> g(PurgeMutex_);
  504. if (Shutdown_)
  505. return;
  506. CondPurge_.WaitI(PurgeMutex_);
  507. }
  508. PurgeCache();
  509. AtomicUnlock(&InPurging_);
  510. }
  511. }
  512. void PurgeCache() noexcept {
  513. //try remove at least ExceedSoftLimit() oldest connections from cache
  514. //вычисляем долю кеша, которую нужно почистить (в 256 долях) (но не менее 1/32 кеша)
  515. const size_t frac256 = Min<size_t>(256, Max<size_t>(8, (ExceedSoftLimit() << 8) / (CachedConnections.Val() + 1)));
  516. TConnectionRef tmp;
  517. for (size_t i = 0; i < MaxConnId_.load(std::memory_order_acquire) && !Shutdown_; i++) {
  518. TConnList& tc = Lst_.Get(i);
  519. if (size_t qsize = tc.Size()) {
  520. //в каждой очереди чистим вычисленную долю
  521. size_t purgeCounter = ((qsize * frac256) >> 8);
  522. if (!purgeCounter && qsize) {
  523. if (qsize == 1) {
  524. // check lifeness
  525. TConnectionRef res;
  526. if (tc.Dequeue(&res)) {
  527. // if connection valid put it back
  528. if (IsNotSocketClosedByOtherSide((*res)->Fd()) && !(*res)->ShutdownReceived()) {
  529. tc.Enqueue(res);
  530. } else {
  531. ActiveConnections.Inc();
  532. CachedConnections.Dec();
  533. }
  534. }
  535. } else {
  536. // drop at least one connection from queue with at least 2 connections
  537. purgeCounter = 1;
  538. }
  539. }
  540. while (purgeCounter-- && tc.Dequeue(&tmp)) {
  541. ActiveConnections.Inc();
  542. CachedConnections.Dec();
  543. tmp->Reset(nullptr);
  544. }
  545. }
  546. }
  547. }
  548. inline TConnList& ConnList(const TResolvedHost& addr) {
  549. return Lst_.Get(addr.Id);
  550. }
  551. inline size_t TotalConnections() const noexcept {
  552. return ActiveConnections.Val() + CachedConnections.Val();
  553. }
  554. inline size_t ExceedSoftLimit() const noexcept {
  555. return NHttp::TFdLimits::ExceedLimit(TotalConnections(), Limits.Soft());
  556. }
  557. inline size_t ExceedHardLimit() const noexcept {
  558. return NHttp::TFdLimits::ExceedLimit(TotalConnections(), Limits.Hard());
  559. }
  560. NHttp::TFdLimits Limits;
  561. TAtomicCounter ActiveConnections;
  562. TAtomicCounter CachedConnections;
  563. NHttp::TLockFreeSequence<TConnList> Lst_;
  564. TAtomic InPurging_;
  565. std::atomic<size_t> MaxConnId_;
  566. TAutoPtr<IThreadFactory::IThread> T_;
  567. TCondVar CondPurge_;
  568. TMutex PurgeMutex_;
  569. TAtomicBool Shutdown_;
  570. };
  571. class TSslCtx: public TThrRefBase {
  572. protected:
  573. TSslCtx()
  574. : SslCtx_(nullptr)
  575. {
  576. }
  577. public:
  578. ~TSslCtx() override {
  579. SSL_CTX_free(SslCtx_);
  580. }
  581. operator SSL_CTX*() {
  582. return SslCtx_;
  583. }
  584. protected:
  585. SSL_CTX* SslCtx_;
  586. };
  587. using TSslCtxPtr = TIntrusivePtr<TSslCtx>;
  588. class TSslCtxServer: public TSslCtx {
  589. struct TPasswordCallbackUserData {
  590. TParsedLocation Location;
  591. TString CertFileName;
  592. TString KeyFileName;
  593. };
  594. class TUserDataHolder {
  595. public:
  596. TUserDataHolder(SSL_CTX* ctx, const TParsedLocation& location, const TString& certFileName, const TString& keyFileName)
  597. : SslCtx_(ctx)
  598. , Data_{location, certFileName, keyFileName}
  599. {
  600. SSL_CTX_set_default_passwd_cb_userdata(SslCtx_, &Data_);
  601. }
  602. ~TUserDataHolder() {
  603. SSL_CTX_set_default_passwd_cb_userdata(SslCtx_, nullptr);
  604. }
  605. private:
  606. SSL_CTX* SslCtx_;
  607. TPasswordCallbackUserData Data_;
  608. };
  609. public:
  610. TSslCtxServer(const TParsedLocation& loc) {
  611. const SSL_METHOD* method = SSLv23_server_method();
  612. if (Y_UNLIKELY(!method)) {
  613. ythrow TSslException(TStringBuf("SSLv23_server_method"));
  614. }
  615. SslCtx_ = SSL_CTX_new(method);
  616. if (Y_UNLIKELY(!SslCtx_)) {
  617. ythrow TSslException(TStringBuf("SSL_CTX_new(server)"));
  618. }
  619. TString cert, key;
  620. ParseUserInfo(loc, cert, key);
  621. TUserDataHolder holder(SslCtx_, loc, cert, key);
  622. SSL_CTX_set_default_passwd_cb(SslCtx_, [](char* buf, int size, int rwflag, void* userData) -> int {
  623. Y_UNUSED(rwflag);
  624. Y_UNUSED(userData);
  625. if (THttpsOptions::KeyPasswdCallback == nullptr || userData == nullptr) {
  626. return 0;
  627. }
  628. auto data = static_cast<TPasswordCallbackUserData*>(userData);
  629. const auto& passwd = THttpsOptions::KeyPasswdCallback(data->Location, data->CertFileName, data->KeyFileName);
  630. if (size < static_cast<int>(passwd.size())) {
  631. return -1;
  632. }
  633. return passwd.copy(buf, size, 0);
  634. });
  635. if (!cert || !key) {
  636. ythrow TSslException() << TStringBuf("no certificate or private key is specified for server");
  637. }
  638. if (1 != SSL_CTX_use_certificate_chain_file(SslCtx_, cert.data())) {
  639. ythrow TSslException(TStringBuf("SSL_CTX_use_certificate_chain_file (server)"));
  640. }
  641. if (1 != SSL_CTX_use_PrivateKey_file(SslCtx_, key.data(), SSL_FILETYPE_PEM)) {
  642. ythrow TSslException(TStringBuf("SSL_CTX_use_PrivateKey_file (server)"));
  643. }
  644. if (1 != SSL_CTX_check_private_key(SslCtx_)) {
  645. ythrow TSslException(TStringBuf("SSL_CTX_check_private_key (server)"));
  646. }
  647. }
  648. };
  649. class TSslCtxClient: public TSslCtx {
  650. public:
  651. TSslCtxClient() {
  652. const SSL_METHOD* method = SSLv23_client_method();
  653. if (Y_UNLIKELY(!method)) {
  654. ythrow TSslException(TStringBuf("SSLv23_client_method"));
  655. }
  656. SslCtx_ = SSL_CTX_new(method);
  657. if (Y_UNLIKELY(!SslCtx_)) {
  658. ythrow TSslException(TStringBuf("SSL_CTX_new(client)"));
  659. }
  660. const TString& caFile = THttpsOptions::CAFile;
  661. const TString& caPath = THttpsOptions::CAPath;
  662. if (caFile || caPath) {
  663. if (!SSL_CTX_load_verify_locations(SslCtx_, caFile ? caFile.data() : nullptr, caPath ? caPath.data() : nullptr)) {
  664. ythrow TSslException(TStringBuf("SSL_CTX_load_verify_locations(client)"));
  665. }
  666. }
  667. SSL_CTX_set_options(SslCtx_, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION);
  668. if (THttpsOptions::ClientVerifyCallback) {
  669. SSL_CTX_set_verify(SslCtx_, SSL_VERIFY_PEER, THttpsOptions::ClientVerifyCallback);
  670. } else {
  671. SSL_CTX_set_verify(SslCtx_, SSL_VERIFY_NONE, nullptr);
  672. }
  673. const TString& clientCertificate = THttpsOptions::ClientCertificate;
  674. const TString& clientPrivateKey = THttpsOptions::ClientPrivateKey;
  675. if (clientCertificate && clientPrivateKey) {
  676. SSL_CTX_set_default_passwd_cb(SslCtx_, [](char* buf, int size, int rwflag, void* userData) -> int {
  677. Y_UNUSED(rwflag);
  678. Y_UNUSED(userData);
  679. const TString& clientPrivateKeyPwd = THttpsOptions::ClientPrivateKeyPassword;
  680. if (!clientPrivateKeyPwd) {
  681. return 0;
  682. }
  683. if (size < static_cast<int>(clientPrivateKeyPwd.size())) {
  684. return -1;
  685. }
  686. return clientPrivateKeyPwd.copy(buf, size, 0);
  687. });
  688. if (1 != SSL_CTX_use_certificate_chain_file(SslCtx_, clientCertificate.c_str())) {
  689. ythrow TSslException(TStringBuf("SSL_CTX_use_certificate_chain_file (client)"));
  690. }
  691. if (1 != SSL_CTX_use_PrivateKey_file(SslCtx_, clientPrivateKey.c_str(), SSL_FILETYPE_PEM)) {
  692. ythrow TSslException(TStringBuf("SSL_CTX_use_PrivateKey_file (client)"));
  693. }
  694. if (1 != SSL_CTX_check_private_key(SslCtx_)) {
  695. ythrow TSslException(TStringBuf("SSL_CTX_check_private_key (client)"));
  696. }
  697. } else if (clientCertificate || clientPrivateKey) {
  698. ythrow TSslException() << TStringBuf("both certificate and private key must be specified for client");
  699. }
  700. }
  701. static TSslCtxClient& Instance() {
  702. return *Singleton<TSslCtxClient>();
  703. }
  704. };
  705. class TContBIO : public NOpenSSL::TAbstractIO {
  706. public:
  707. TContBIO(SOCKET s, const TAtomicBool* canceled = nullptr)
  708. : Timeout_(TDuration::MicroSeconds(10000))
  709. , S_(s)
  710. , Canceled_(canceled)
  711. , Cont_(nullptr)
  712. {
  713. }
  714. SOCKET Socket() {
  715. return S_;
  716. }
  717. int PollT(int what, const TDuration& timeout) {
  718. return NCoro::PollT(Cont_, Socket(), what, timeout);
  719. }
  720. void WaitUntilWritten() {
  721. #if defined(FIONWRITE)
  722. if (Y_LIKELY(Cont_)) {
  723. int err;
  724. int nbytes = Max<int>();
  725. TDuration tout = TDuration::MilliSeconds(10);
  726. while (((err = ioctl(S_, FIONWRITE, &nbytes)) == 0) && nbytes) {
  727. err = NCoro::PollT(Cont_, S_, CONT_POLL_READ, tout);
  728. if (!err) {
  729. //wait complete, cause have some data
  730. break;
  731. }
  732. if (err != ETIMEDOUT) {
  733. ythrow TSystemError(err) << TStringBuf("request failed");
  734. }
  735. tout = tout * 2;
  736. }
  737. if (err) {
  738. ythrow TSystemError() << TStringBuf("ioctl() failed");
  739. }
  740. } else {
  741. ythrow TSslException() << TStringBuf("No cont available");
  742. }
  743. #endif
  744. }
  745. void AcquireCont(TCont* c) {
  746. Cont_ = c;
  747. }
  748. void ReleaseCont() {
  749. Cont_ = nullptr;
  750. }
  751. int Write(const char* data, size_t dlen, size_t* written) override {
  752. if (Y_UNLIKELY(!Cont_)) {
  753. return -1;
  754. }
  755. while (true) {
  756. auto done = NCoro::WriteI(Cont_, S_, data, dlen);
  757. if (done.Status() != EAGAIN) {
  758. *written = done.Checked();
  759. return 1;
  760. }
  761. }
  762. }
  763. int Read(char* data, size_t dlen, size_t* readbytes) override {
  764. if (Y_UNLIKELY(!Cont_)) {
  765. return -1;
  766. }
  767. if (!Canceled_) {
  768. while (true) {
  769. auto done = NCoro::ReadI(Cont_, S_, data, dlen);
  770. if (EAGAIN != done.Status()) {
  771. *readbytes = done.Processed();
  772. return 1;
  773. }
  774. }
  775. }
  776. while (true) {
  777. if (*Canceled_) {
  778. return SSL_RVAL_TIMEOUT;
  779. }
  780. TContIOStatus ioStat(NCoro::ReadT(Cont_, S_, data, dlen, Timeout_));
  781. if (ioStat.Status() == ETIMEDOUT) {
  782. //increase to 1.5 times every iteration (to 1sec floor)
  783. Timeout_ = TDuration::MicroSeconds(Min<ui64>(1000000, Timeout_.MicroSeconds() + (Timeout_.MicroSeconds() >> 1)));
  784. continue;
  785. }
  786. *readbytes = ioStat.Processed();
  787. return 1;
  788. }
  789. }
  790. int Puts(const char* buf) override {
  791. Y_UNUSED(buf);
  792. return -1;
  793. }
  794. int Gets(char* buf, int size) override {
  795. Y_UNUSED(buf);
  796. Y_UNUSED(size);
  797. return -1;
  798. }
  799. void Flush() override {
  800. }
  801. private:
  802. TDuration Timeout_;
  803. SOCKET S_;
  804. const TAtomicBool* Canceled_;
  805. TCont* Cont_;
  806. };
  807. class TSslIOStream: public IInputStream, public IOutputStream {
  808. protected:
  809. TSslIOStream(TSslCtx& sslCtx, TAutoPtr<TContBIO> connection)
  810. : Connection_(connection)
  811. , SslCtx_(sslCtx)
  812. , Ssl_(nullptr)
  813. {
  814. }
  815. virtual void Handshake() = 0;
  816. public:
  817. void WaitUntilWritten() {
  818. if (Connection_) {
  819. Connection_->WaitUntilWritten();
  820. }
  821. }
  822. int PollReadT(const TDuration& timeout) {
  823. if (!Connection_) {
  824. return -1;
  825. }
  826. while (true) {
  827. const int rpoll = Connection_->PollT(CONT_POLL_READ, timeout);
  828. if (!Ssl_ || rpoll) {
  829. return rpoll;
  830. }
  831. char c = 0;
  832. const int rpeek = SSL_peek(Ssl_.Get(), &c, sizeof(c));
  833. if (rpeek < 0) {
  834. return -1;
  835. } else if (rpeek > 0) {
  836. return 0;
  837. } else {
  838. if ((SSL_get_shutdown(Ssl_.Get()) & SSL_RECEIVED_SHUTDOWN) != 0) {
  839. Shutdown(); // wait until shutdown is finished
  840. return EIO;
  841. }
  842. }
  843. }
  844. }
  845. void Shutdown() {
  846. if (Ssl_ && Connection_) {
  847. for (size_t i = 0; i < 2; ++i) {
  848. bool rval = SSL_shutdown(Ssl_.Get());
  849. if (0 == rval) {
  850. continue;
  851. } else if (1 == rval) {
  852. break;
  853. }
  854. }
  855. }
  856. }
  857. inline void AcquireCont(TCont* c) {
  858. if (Y_UNLIKELY(!Connection_)) {
  859. ythrow TSslException() << TStringBuf("no connection provided");
  860. }
  861. Connection_->AcquireCont(c);
  862. }
  863. inline void ReleaseCont() {
  864. if (Connection_) {
  865. Connection_->ReleaseCont();
  866. }
  867. }
  868. TContIOStatus WriteVectorI(const TList<IOutputStream::TPart>& vec) {
  869. for (const auto& p : vec) {
  870. Write(p.buf, p.len);
  871. }
  872. return TContIOStatus::Success(vec.size());
  873. }
  874. SOCKET Socket() {
  875. if (Y_UNLIKELY(!Connection_)) {
  876. ythrow TSslException() << TStringBuf("no connection provided");
  877. }
  878. return Connection_->Socket();
  879. }
  880. private:
  881. void DoWrite(const void* buf, size_t len) override {
  882. if (Y_UNLIKELY(!Connection_)) {
  883. ythrow TSslException() << TStringBuf("DoWrite() no connection provided");
  884. }
  885. const int rval = SSL_write(Ssl_.Get(), buf, len);
  886. if (rval <= 0) {
  887. ythrow TSslException(TStringBuf("SSL_write"), Ssl_.Get(), rval);
  888. }
  889. }
  890. size_t DoRead(void* buf, size_t len) override {
  891. if (Y_UNLIKELY(!Connection_)) {
  892. ythrow TSslException() << TStringBuf("DoRead() no connection provided");
  893. }
  894. const int rval = SSL_read(Ssl_.Get(), buf, len);
  895. if (rval < 0) {
  896. if (SSL_RVAL_TIMEOUT == rval) {
  897. ythrow TSystemError(ECANCELED) << TStringBuf(" http request canceled");
  898. }
  899. ythrow TSslException(TStringBuf("SSL_read"), Ssl_.Get(), rval);
  900. } else if (0 == rval) {
  901. if ((SSL_get_shutdown(Ssl_.Get()) & SSL_RECEIVED_SHUTDOWN) != 0) {
  902. return rval;
  903. } else {
  904. const int err = SSL_get_error(Ssl_.Get(), rval);
  905. if (SSL_ERROR_ZERO_RETURN != err) {
  906. ythrow TSslException(TStringBuf("SSL_read"), Ssl_.Get(), rval);
  907. }
  908. }
  909. }
  910. return static_cast<size_t>(rval);
  911. }
  912. protected:
  913. // just for ssl debug
  914. static void InfoCB(const SSL* s, int where, int ret) {
  915. TStringBuf str;
  916. const int w = where & ~SSL_ST_MASK;
  917. if (w & SSL_ST_CONNECT) {
  918. str = TStringBuf("SSL_connect");
  919. } else if (w & SSL_ST_ACCEPT) {
  920. str = TStringBuf("SSL_accept");
  921. } else {
  922. str = TStringBuf("undefined");
  923. }
  924. if (where & SSL_CB_LOOP) {
  925. Cerr << str << ':' << SSL_state_string_long(s) << Endl;
  926. } else if (where & SSL_CB_ALERT) {
  927. Cerr << TStringBuf("SSL3 alert ") << ((where & SSL_CB_READ) ? TStringBuf("read") : TStringBuf("write")) << ' ' << SSL_alert_type_string_long(ret) << ':' << SSL_alert_desc_string_long(ret) << Endl;
  928. } else if (where & SSL_CB_EXIT) {
  929. if (ret == 0) {
  930. Cerr << str << TStringBuf(":failed in ") << SSL_state_string_long(s) << Endl;
  931. } else if (ret < 0) {
  932. Cerr << str << TStringBuf(":error in ") << SSL_state_string_long(s) << Endl;
  933. }
  934. }
  935. }
  936. protected:
  937. THolder<TContBIO> Connection_;
  938. TSslCtx& SslCtx_;
  939. TSslHolder Ssl_;
  940. };
  941. class TContBIOWatcher {
  942. public:
  943. TContBIOWatcher(TSslIOStream& io, TCont* c) noexcept
  944. : IO_(io)
  945. {
  946. IO_.AcquireCont(c);
  947. }
  948. ~TContBIOWatcher() noexcept {
  949. IO_.ReleaseCont();
  950. }
  951. private:
  952. TSslIOStream& IO_;
  953. };
  954. class TSslClientIOStream: public TSslIOStream {
  955. public:
  956. TSslClientIOStream(TSslCtxClient& sslCtx, const TParsedLocation& loc, SOCKET s, const TAtomicBool* canceled)
  957. : TSslIOStream(sslCtx, new TContBIO(s, canceled))
  958. , Location_(loc)
  959. {
  960. }
  961. void SetSsl(TSslHolder&& ssl) {
  962. Ssl_ = std::move(ssl);
  963. BIO_up_ref(*Connection_);
  964. SSL_set_bio(Ssl_.Get(), *Connection_, *Connection_);
  965. }
  966. TSslHolder&& MoveSsl() {
  967. return std::move(Ssl_);
  968. }
  969. void Handshake() override {
  970. Ssl_.Reset(SSL_new(SslCtx_));
  971. if (THttpsOptions::EnableSslClientDebug) {
  972. SSL_set_info_callback(Ssl_.Get(), InfoCB);
  973. }
  974. BIO_up_ref(*Connection_); // SSL_set_bio consumes only one reference if rbio and wbio are the same
  975. SSL_set_bio(Ssl_.Get(), *Connection_, *Connection_);
  976. const TString hostname(Location_.Host);
  977. const int rev = SSL_set_tlsext_host_name(Ssl_.Get(), hostname.data());
  978. if (Y_UNLIKELY(1 != rev)) {
  979. ythrow TSslException(TStringBuf("SSL_set_tlsext_host_name(client)"), Ssl_.Get(), rev);
  980. }
  981. TString cert, pvtKey;
  982. ParseUserInfo(Location_, cert, pvtKey);
  983. if (cert && (1 != SSL_use_certificate_file(Ssl_.Get(), cert.data(), SSL_FILETYPE_PEM))) {
  984. ythrow TSslException(TStringBuf("SSL_use_certificate_file(client)"));
  985. }
  986. if (pvtKey) {
  987. if (1 != SSL_use_PrivateKey_file(Ssl_.Get(), pvtKey.data(), SSL_FILETYPE_PEM)) {
  988. ythrow TSslException(TStringBuf("SSL_use_PrivateKey_file(client)"));
  989. }
  990. if (1 != SSL_check_private_key(Ssl_.Get())) {
  991. ythrow TSslException(TStringBuf("SSL_check_private_key(client)"));
  992. }
  993. }
  994. SSL_set_connect_state(Ssl_.Get());
  995. // TODO restore session if reconnect
  996. const int rval = SSL_do_handshake(Ssl_.Get());
  997. if (1 != rval) {
  998. if (rval == SSL_RVAL_TIMEOUT) {
  999. ythrow TSystemError(ECANCELED) << TStringBuf("canceled");
  1000. } else {
  1001. ythrow TSslException(TStringBuf("BIO_do_handshake(client)"), Ssl_.Get(), rval);
  1002. }
  1003. }
  1004. if (THttpsOptions::CheckCertificateHostname) {
  1005. TX509Holder peerCert(SSL_get_peer_certificate(Ssl_.Get()));
  1006. if (!peerCert) {
  1007. ythrow TSslException(TStringBuf("SSL_get_peer_certificate(client)"));
  1008. }
  1009. if (!CheckCertHostname(peerCert.Get(), Location_.Host)) {
  1010. ythrow TSslException(TStringBuf("CheckCertHostname(client)"));
  1011. }
  1012. }
  1013. }
  1014. private:
  1015. const TParsedLocation Location_;
  1016. //TSslSessionHolder Session_;
  1017. };
  1018. static TConnCache* ConnectionCache() {
  1019. return Singleton<TConnCache>();
  1020. }
  1021. //some templates magic
  1022. template <class T>
  1023. static inline TAutoPtr<T> AutoPtr(T* t) noexcept {
  1024. return t;
  1025. }
  1026. static inline TString ReadAll(THttpInput& in) {
  1027. TString ret;
  1028. ui64 clin;
  1029. if (in.GetContentLength(clin)) {
  1030. const size_t cl = SafeIntegerCast<size_t>(clin);
  1031. ret.ReserveAndResize(cl);
  1032. size_t sz = in.Load(ret.begin(), cl);
  1033. if (sz != cl) {
  1034. throw yexception() << TStringBuf("not full content: ") << sz << TStringBuf(" bytes from ") << cl;
  1035. }
  1036. } else if (in.HasContent()) {
  1037. TVector<char> buff(9500); //common jumbo frame size
  1038. while (size_t len = in.Read(buff.data(), buff.size())) {
  1039. ret.AppendNoAlias(buff.data(), len);
  1040. }
  1041. }
  1042. return ret;
  1043. }
  1044. template <class TRequestType>
  1045. class THttpsRequest: public IJob {
  1046. public:
  1047. inline THttpsRequest(TSimpleHandleRef hndl, TMessage msg)
  1048. : Hndl_(hndl)
  1049. , Msg_(std::move(msg))
  1050. , Loc_(Msg_.Addr)
  1051. , Addr_(CachedThrResolve(TResolveInfo(Loc_.Host, Loc_.GetPort())))
  1052. {
  1053. }
  1054. void DoRun(TCont* c) override {
  1055. THolder<THttpsRequest> This(this);
  1056. if (c->Cancelled()) {
  1057. Hndl_->NotifyError(new TError("canceled", TError::TType::Cancelled));
  1058. return;
  1059. }
  1060. TErrorRef error;
  1061. TConnCache::TConnectionRef connection(ConnectionCache()->Connect(c, Msg_.Addr, *Addr_, &error));
  1062. if (!connection) {
  1063. Hndl_->NotifyError(error);
  1064. return;
  1065. }
  1066. TSslClientIOStream io(TSslCtxClient::Instance(), Loc_, (*connection)->Fd(), Hndl_->CanceledPtr());
  1067. TContBIOWatcher w(io, c);
  1068. TString received;
  1069. THttpHeaders headers;
  1070. TString firstLine;
  1071. try {
  1072. if ((*connection)->HasSsl()) {
  1073. io.SetSsl((*connection)->MoveSsl());
  1074. } else {
  1075. io.Handshake();
  1076. }
  1077. RequestData().SendTo(io);
  1078. Req_.Destroy();
  1079. error = ProcessRecv(io, &received, &headers, &firstLine);
  1080. (*connection)->SetSsl(io.MoveSsl());
  1081. (*connection)->ResetBIO();
  1082. } catch (const TSystemError& e) {
  1083. if (c->Cancelled() || e.Status() == ECANCELED) {
  1084. error = new TError("canceled", TError::TType::Cancelled);
  1085. } else {
  1086. error = new TError(CurrentExceptionMessage());
  1087. }
  1088. } catch (...) {
  1089. if (c->Cancelled()) {
  1090. error = new TError("canceled", TError::TType::Cancelled);
  1091. } else {
  1092. error = new TError(CurrentExceptionMessage());
  1093. }
  1094. }
  1095. if (error) {
  1096. Hndl_->NotifyError(error, received, firstLine, headers);
  1097. } else {
  1098. ConnectionCache()->Release(connection);
  1099. Hndl_->NotifyResponse(received, firstLine, headers);
  1100. }
  1101. }
  1102. TErrorRef ProcessRecv(TSslClientIOStream& io, TString* data, THttpHeaders* headers, TString* firstLine) {
  1103. io.WaitUntilWritten();
  1104. Hndl_->SetSendComplete();
  1105. THttpInput in(&io);
  1106. *data = ReadAll(in);
  1107. *firstLine = in.FirstLine();
  1108. *headers = in.Headers();
  1109. i32 code = ParseHttpRetCode(in.FirstLine());
  1110. if (code < 200 || code > (!THttpsOptions::RedirectionNotError ? 299 : 399)) {
  1111. return new TError(TStringBuilder() << TStringBuf("request failed(") << in.FirstLine() << ')', TError::TType::ProtocolSpecific, code);
  1112. }
  1113. return nullptr;
  1114. }
  1115. const NHttp::TRequestData& RequestData() {
  1116. if (!Req_) {
  1117. Req_ = TRequestType::Build(Msg_, Loc_);
  1118. }
  1119. return *Req_;
  1120. }
  1121. private:
  1122. TSimpleHandleRef Hndl_;
  1123. const TMessage Msg_;
  1124. const TParsedLocation Loc_;
  1125. const TResolvedHost* Addr_;
  1126. NHttp::TRequestData::TPtr Req_;
  1127. };
  1128. class TServer: public IRequester, public TContListener::ICallBack {
  1129. class TSslServerIOStream: public TSslIOStream, public TThrRefBase {
  1130. public:
  1131. TSslServerIOStream(TSslCtxServer& sslCtx, TSocketRef s)
  1132. : TSslIOStream(sslCtx, new TContBIO(*s))
  1133. , S_(s)
  1134. {
  1135. }
  1136. void Close(bool shutdown) {
  1137. if (shutdown) {
  1138. Shutdown();
  1139. }
  1140. S_->Close();
  1141. }
  1142. void Handshake() override {
  1143. if (!Ssl_) {
  1144. Ssl_.Reset(SSL_new(SslCtx_));
  1145. if (THttpsOptions::EnableSslServerDebug) {
  1146. SSL_set_info_callback(Ssl_.Get(), InfoCB);
  1147. }
  1148. BIO_up_ref(*Connection_); // SSL_set_bio consumes only one reference if rbio and wbio are the same
  1149. SSL_set_bio(Ssl_.Get(), *Connection_, *Connection_);
  1150. const int rc = SSL_accept(Ssl_.Get());
  1151. if (1 != rc) {
  1152. ythrow TSslException(TStringBuf("SSL_accept"), Ssl_.Get(), rc);
  1153. }
  1154. }
  1155. if (!SSL_is_init_finished(Ssl_.Get())) {
  1156. const int rc = SSL_do_handshake(Ssl_.Get());
  1157. if (rc != 1) {
  1158. ythrow TSslException(TStringBuf("SSL_do_handshake"), Ssl_.Get(), rc);
  1159. }
  1160. }
  1161. }
  1162. private:
  1163. TSocketRef S_;
  1164. };
  1165. class TJobsQueue: public TAutoOneConsumerPipeQueue<IJob>, public TThrRefBase {
  1166. };
  1167. typedef TIntrusivePtr<TJobsQueue> TJobsQueueRef;
  1168. class TWrite: public IJob, public TData {
  1169. private:
  1170. template <class T>
  1171. static void WriteHeader(IOutputStream& os, TStringBuf name, T value) {
  1172. os << name << TStringBuf(": ") << value << TStringBuf("\r\n");
  1173. }
  1174. static void WriteHttpCode(IOutputStream& os, TMaybe<IRequest::TResponseError> error) {
  1175. if (!error.Defined()) {
  1176. os << HttpCodeStrEx(HttpCodes::HTTP_OK);
  1177. return;
  1178. }
  1179. switch (*error) {
  1180. case IRequest::TResponseError::BadRequest:
  1181. os << HttpCodeStrEx(HttpCodes::HTTP_BAD_REQUEST);
  1182. break;
  1183. case IRequest::TResponseError::Forbidden:
  1184. os << HttpCodeStrEx(HttpCodes::HTTP_FORBIDDEN);
  1185. break;
  1186. case IRequest::TResponseError::NotExistService:
  1187. os << HttpCodeStrEx(HttpCodes::HTTP_NOT_FOUND);
  1188. break;
  1189. case IRequest::TResponseError::TooManyRequests:
  1190. os << HttpCodeStrEx(HttpCodes::HTTP_TOO_MANY_REQUESTS);
  1191. break;
  1192. case IRequest::TResponseError::InternalError:
  1193. os << HttpCodeStrEx(HttpCodes::HTTP_INTERNAL_SERVER_ERROR);
  1194. break;
  1195. case IRequest::TResponseError::NotImplemented:
  1196. os << HttpCodeStrEx(HttpCodes::HTTP_NOT_IMPLEMENTED);
  1197. break;
  1198. case IRequest::TResponseError::BadGateway:
  1199. os << HttpCodeStrEx(HttpCodes::HTTP_BAD_GATEWAY);
  1200. break;
  1201. case IRequest::TResponseError::ServiceUnavailable:
  1202. os << HttpCodeStrEx(HttpCodes::HTTP_SERVICE_UNAVAILABLE);
  1203. break;
  1204. case IRequest::TResponseError::BandwidthLimitExceeded:
  1205. os << HttpCodeStrEx(HttpCodes::HTTP_BANDWIDTH_LIMIT_EXCEEDED);
  1206. break;
  1207. case IRequest::TResponseError::MaxResponseError:
  1208. ythrow yexception() << TStringBuf("unknow type of error");
  1209. }
  1210. }
  1211. public:
  1212. inline TWrite(TData& data, const TString& compressionScheme, TIntrusivePtr<TSslServerIOStream> io, TServer* server, const TString& headers, int httpCode)
  1213. : CompressionScheme_(compressionScheme)
  1214. , IO_(io)
  1215. , Server_(server)
  1216. , Error_(TMaybe<IRequest::TResponseError>())
  1217. , Headers_(headers)
  1218. , HttpCode_(httpCode)
  1219. {
  1220. swap(data);
  1221. }
  1222. inline TWrite(TData& data, const TString& compressionScheme, TIntrusivePtr<TSslServerIOStream> io, TServer* server, IRequest::TResponseError error, const TString& headers)
  1223. : CompressionScheme_(compressionScheme)
  1224. , IO_(io)
  1225. , Server_(server)
  1226. , Error_(error)
  1227. , Headers_(headers)
  1228. , HttpCode_(0)
  1229. {
  1230. swap(data);
  1231. }
  1232. void DoRun(TCont* c) override {
  1233. THolder<TWrite> This(this);
  1234. try {
  1235. TContBIOWatcher w(*IO_, c);
  1236. PrepareSocket(IO_->Socket());
  1237. char buf[128];
  1238. TMemoryOutput mo(buf, sizeof(buf));
  1239. mo << TStringBuf("HTTP/1.1 ");
  1240. if (HttpCode_) {
  1241. mo << HttpCodeStrEx(HttpCode_);
  1242. } else {
  1243. WriteHttpCode(mo, Error_);
  1244. }
  1245. mo << TStringBuf("\r\n");
  1246. if (!CompressionScheme_.empty()) {
  1247. WriteHeader(mo, TStringBuf("Content-Encoding"), TStringBuf(CompressionScheme_));
  1248. }
  1249. WriteHeader(mo, TStringBuf("Connection"), TStringBuf("Keep-Alive"));
  1250. WriteHeader(mo, TStringBuf("Content-Length"), size());
  1251. mo << Headers_;
  1252. mo << TStringBuf("\r\n");
  1253. IO_->Write(buf, mo.Buf() - buf);
  1254. if (size()) {
  1255. IO_->Write(data(), size());
  1256. }
  1257. Server_->Enqueue(new TRead(IO_, Server_));
  1258. } catch (...) {
  1259. }
  1260. }
  1261. private:
  1262. const TString CompressionScheme_;
  1263. TIntrusivePtr<TSslServerIOStream> IO_;
  1264. TServer* Server_;
  1265. TMaybe<IRequest::TResponseError> Error_;
  1266. TString Headers_;
  1267. int HttpCode_;
  1268. };
  1269. class TRequest: public IHttpRequest {
  1270. public:
  1271. inline TRequest(THttpInput& in, TIntrusivePtr<TSslServerIOStream> io, TServer* server)
  1272. : IO_(io)
  1273. , Tmp_(in.FirstLine())
  1274. , CompressionScheme_(in.BestCompressionScheme())
  1275. , RemoteHost_(PrintHostByRfc(*GetPeerAddr(IO_->Socket())))
  1276. , Headers_(in.Headers())
  1277. , H_(Tmp_)
  1278. , Server_(server)
  1279. {
  1280. }
  1281. ~TRequest() override {
  1282. if (!!IO_) {
  1283. try {
  1284. Server_->Enqueue(new TFail(IO_, Server_));
  1285. } catch (...) {
  1286. }
  1287. }
  1288. }
  1289. TStringBuf Scheme() const override {
  1290. return TStringBuf("https");
  1291. }
  1292. TString RemoteHost() const override {
  1293. return RemoteHost_;
  1294. }
  1295. const THttpHeaders& Headers() const override {
  1296. return Headers_;
  1297. }
  1298. TStringBuf Method() const override {
  1299. return H_.Method;
  1300. }
  1301. TStringBuf Cgi() const override {
  1302. return H_.Cgi;
  1303. }
  1304. TStringBuf Service() const override {
  1305. return TStringBuf(H_.Path).Skip(1);
  1306. }
  1307. TStringBuf RequestId() const override {
  1308. return TStringBuf();
  1309. }
  1310. bool Canceled() const override {
  1311. if (!IO_) {
  1312. return false;
  1313. }
  1314. return !IsNotSocketClosedByOtherSide(IO_->Socket());
  1315. }
  1316. void SendReply(TData& data) override {
  1317. SendReply(data, TString(), HttpCodes::HTTP_OK);
  1318. }
  1319. void SendReply(TData& data, const TString& headers, int httpCode) override {
  1320. const bool compressed = Compress(data);
  1321. Server_->Enqueue(new TWrite(data, compressed ? CompressionScheme_ : TString(), IO_, Server_, headers, httpCode));
  1322. Y_UNUSED(IO_.Release());
  1323. }
  1324. void SendError(TResponseError error, const THttpErrorDetails& details) override {
  1325. TData data;
  1326. Server_->Enqueue(new TWrite(data, TString(), IO_, Server_, error, details.Headers));
  1327. Y_UNUSED(IO_.Release());
  1328. }
  1329. private:
  1330. bool Compress(TData& data) const {
  1331. if (CompressionScheme_ == TStringBuf("gzip")) {
  1332. try {
  1333. TData gzipped(data.size());
  1334. TMemoryOutput out(gzipped.data(), gzipped.size());
  1335. TZLibCompress c(&out, ZLib::GZip);
  1336. c.Write(data.data(), data.size());
  1337. c.Finish();
  1338. gzipped.resize(out.Buf() - gzipped.data());
  1339. data.swap(gzipped);
  1340. return true;
  1341. } catch (yexception&) {
  1342. // gzipped data occupies more space than original data
  1343. }
  1344. }
  1345. return false;
  1346. }
  1347. private:
  1348. TIntrusivePtr<TSslServerIOStream> IO_;
  1349. const TString Tmp_;
  1350. const TString CompressionScheme_;
  1351. const TString RemoteHost_;
  1352. const THttpHeaders Headers_;
  1353. protected:
  1354. TParsedHttpFull H_;
  1355. TServer* Server_;
  1356. };
  1357. class TGetRequest: public TRequest {
  1358. public:
  1359. inline TGetRequest(THttpInput& in, TIntrusivePtr<TSslServerIOStream> io, TServer* server)
  1360. : TRequest(in, io, server)
  1361. {
  1362. }
  1363. TStringBuf Data() const override {
  1364. return H_.Cgi;
  1365. }
  1366. TStringBuf Body() const override {
  1367. return TStringBuf();
  1368. }
  1369. };
  1370. class TPostRequest: public TRequest {
  1371. public:
  1372. inline TPostRequest(THttpInput& in, TIntrusivePtr<TSslServerIOStream> io, TServer* server)
  1373. : TRequest(in, io, server)
  1374. , Data_(ReadAll(in))
  1375. {
  1376. }
  1377. TStringBuf Data() const override {
  1378. return Data_;
  1379. }
  1380. TStringBuf Body() const override {
  1381. return Data_;
  1382. }
  1383. private:
  1384. TString Data_;
  1385. };
  1386. class TFail: public IJob {
  1387. public:
  1388. inline TFail(TIntrusivePtr<TSslServerIOStream> io, TServer* server)
  1389. : IO_(io)
  1390. , Server_(server)
  1391. {
  1392. }
  1393. void DoRun(TCont* c) override {
  1394. THolder<TFail> This(this);
  1395. constexpr TStringBuf answer = "HTTP/1.1 503 Service unavailable\r\n"
  1396. "Content-Length: 0\r\n\r\n"sv;
  1397. try {
  1398. TContBIOWatcher w(*IO_, c);
  1399. IO_->Write(answer);
  1400. Server_->Enqueue(new TRead(IO_, Server_));
  1401. } catch (...) {
  1402. }
  1403. }
  1404. private:
  1405. TIntrusivePtr<TSslServerIOStream> IO_;
  1406. TServer* Server_;
  1407. };
  1408. class TRead: public IJob {
  1409. public:
  1410. TRead(TIntrusivePtr<TSslServerIOStream> io, TServer* server, bool selfRemove = false)
  1411. : IO_(io)
  1412. , Server_(server)
  1413. , SelfRemove(selfRemove)
  1414. {
  1415. }
  1416. inline void operator()(TCont* c) {
  1417. try {
  1418. TContBIOWatcher w(*IO_, c);
  1419. if (IO_->PollReadT(TDuration::Seconds(InputConnections()->UnusedConnKeepaliveTimeout()))) {
  1420. IO_->Close(true);
  1421. return;
  1422. }
  1423. IO_->Handshake();
  1424. THttpInput in(IO_.Get());
  1425. const char sym = *in.FirstLine().data();
  1426. if (sym == 'p' || sym == 'P') {
  1427. Server_->OnRequest(new TPostRequest(in, IO_, Server_));
  1428. } else {
  1429. Server_->OnRequest(new TGetRequest(in, IO_, Server_));
  1430. }
  1431. } catch (...) {
  1432. IO_->Close(false);
  1433. }
  1434. if (SelfRemove) {
  1435. delete this;
  1436. }
  1437. }
  1438. private:
  1439. void DoRun(TCont* c) override {
  1440. THolder<TRead> This(this);
  1441. (*this)(c);
  1442. }
  1443. private:
  1444. TIntrusivePtr<TSslServerIOStream> IO_;
  1445. TServer* Server_;
  1446. bool SelfRemove = false;
  1447. };
  1448. public:
  1449. inline TServer(IOnRequest* cb, const TParsedLocation& loc)
  1450. : CB_(cb)
  1451. , E_(RealStackSize(16000))
  1452. , L_(new TContListener(this, &E_, TContListener::TOptions().SetDeferAccept(true)))
  1453. , JQ_(new TJobsQueue())
  1454. , SslCtx_(loc)
  1455. {
  1456. L_->Bind(TNetworkAddress(loc.GetPort()));
  1457. E_.Create<TServer, &TServer::RunDispatcher>(this, "dispatcher");
  1458. Thrs_.push_back(Spawn<TServer, &TServer::Run>(this));
  1459. }
  1460. ~TServer() override {
  1461. JQ_->Enqueue(nullptr);
  1462. for (size_t i = 0; i < Thrs_.size(); ++i) {
  1463. Thrs_[i]->Join();
  1464. }
  1465. }
  1466. void Run() {
  1467. //SetHighestThreadPriority();
  1468. L_->Listen();
  1469. E_.Execute();
  1470. }
  1471. inline void OnRequest(const IRequestRef& req) {
  1472. CB_->OnRequest(req);
  1473. }
  1474. TJobsQueueRef& JobQueue() noexcept {
  1475. return JQ_;
  1476. }
  1477. void Enqueue(IJob* j) {
  1478. JQ_->EnqueueSafe(TAutoPtr<IJob>(j));
  1479. }
  1480. void RunDispatcher(TCont* c) {
  1481. for (;;) {
  1482. TAutoPtr<IJob> job(JQ_->Dequeue(c));
  1483. if (!job) {
  1484. break;
  1485. }
  1486. try {
  1487. c->Executor()->Create(*job, "https-job");
  1488. Y_UNUSED(job.Release());
  1489. } catch (...) {
  1490. }
  1491. }
  1492. JQ_->Enqueue(nullptr);
  1493. c->Executor()->Abort();
  1494. }
  1495. void OnAcceptFull(const TAcceptFull& a) override {
  1496. try {
  1497. TSocketRef s(new TSharedSocket(*a.S));
  1498. if (InputConnections()->ExceedHardLimit()) {
  1499. s->Close();
  1500. return;
  1501. }
  1502. THolder<TRead> read(new TRead(new TSslServerIOStream(SslCtx_, s), this, /* selfRemove */ true));
  1503. E_.Create(*read, "https-response");
  1504. Y_UNUSED(read.Release());
  1505. E_.Running()->Yield();
  1506. } catch (...) {
  1507. }
  1508. }
  1509. void OnError() override {
  1510. try {
  1511. throw;
  1512. } catch (const TSystemError& e) {
  1513. //crutch for prevent 100% busyloop (simple suspend listener/accepter)
  1514. if (e.Status() == EMFILE) {
  1515. E_.Running()->SleepT(TDuration::MilliSeconds(500));
  1516. }
  1517. }
  1518. }
  1519. private:
  1520. IOnRequest* CB_;
  1521. TContExecutor E_;
  1522. THolder<TContListener> L_;
  1523. TVector<TThreadRef> Thrs_;
  1524. TJobsQueueRef JQ_;
  1525. TSslCtxServer SslCtx_;
  1526. };
  1527. template <class T>
  1528. class THttpsProtocol: public IProtocol {
  1529. public:
  1530. IRequesterRef CreateRequester(IOnRequest* cb, const TParsedLocation& loc) override {
  1531. return new TServer(cb, loc);
  1532. }
  1533. THandleRef ScheduleRequest(const TMessage& msg, IOnRecv* fallback, TServiceStatRef& ss) override {
  1534. TSimpleHandleRef ret(new TSimpleHandle(fallback, msg, !ss ? nullptr : new TStatCollector(ss)));
  1535. try {
  1536. TAutoPtr<THttpsRequest<T>> req(new THttpsRequest<T>(ret, msg));
  1537. JobQueue()->Schedule(req);
  1538. return ret.Get();
  1539. } catch (...) {
  1540. ret->ResetOnRecv();
  1541. throw;
  1542. }
  1543. }
  1544. TStringBuf Scheme() const noexcept override {
  1545. return T::Name();
  1546. }
  1547. bool SetOption(TStringBuf name, TStringBuf value) override {
  1548. return THttpsOptions::Set(name, value);
  1549. }
  1550. };
  1551. struct TRequestGet: public NHttp::TRequestGet {
  1552. static inline TStringBuf Name() noexcept {
  1553. return TStringBuf("https");
  1554. }
  1555. };
  1556. struct TRequestFull: public NHttp::TRequestFull {
  1557. static inline TStringBuf Name() noexcept {
  1558. return TStringBuf("fulls");
  1559. }
  1560. };
  1561. struct TRequestPost: public NHttp::TRequestPost {
  1562. static inline TStringBuf Name() noexcept {
  1563. return TStringBuf("posts");
  1564. }
  1565. };
  1566. }
  1567. }
  1568. namespace NNeh {
  1569. IProtocol* SSLGetProtocol() {
  1570. return Singleton<NHttps::THttpsProtocol<NNeh::NHttps::TRequestGet>>();
  1571. }
  1572. IProtocol* SSLPostProtocol() {
  1573. return Singleton<NHttps::THttpsProtocol<NNeh::NHttps::TRequestPost>>();
  1574. }
  1575. IProtocol* SSLFullProtocol() {
  1576. return Singleton<NHttps::THttpsProtocol<NNeh::NHttps::TRequestFull>>();
  1577. }
  1578. void SetHttpOutputConnectionsLimits(size_t softLimit, size_t hardLimit) {
  1579. Y_ABORT_UNLESS(
  1580. hardLimit > softLimit,
  1581. "invalid output fd limits; hardLimit=%" PRISZT ", softLimit=%" PRISZT,
  1582. hardLimit, softLimit);
  1583. NHttps::ConnectionCache()->SetFdLimits(softLimit, hardLimit);
  1584. }
  1585. void SetHttpInputConnectionsLimits(size_t softLimit, size_t hardLimit) {
  1586. Y_ABORT_UNLESS(
  1587. hardLimit > softLimit,
  1588. "invalid output fd limits; hardLimit=%" PRISZT ", softLimit=%" PRISZT,
  1589. hardLimit, softLimit);
  1590. NHttps::InputConnections()->SetFdLimits(softLimit, hardLimit);
  1591. }
  1592. void SetHttpInputConnectionsTimeouts(unsigned minSec, unsigned maxSec) {
  1593. Y_ABORT_UNLESS(
  1594. maxSec > minSec,
  1595. "invalid input fd limits timeouts; maxSec=%u, minSec=%u",
  1596. maxSec, minSec);
  1597. NHttps::InputConnections()->MinUnusedConnKeepaliveTimeout.store(minSec, std::memory_order_release);
  1598. NHttps::InputConnections()->MaxUnusedConnKeepaliveTimeout.store(maxSec, std::memory_order_release);
  1599. }
  1600. }