nsHostResolver.cpp 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. /* vim:set ts=4 sw=4 sts=4 et cin: */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #if defined(HAVE_RES_NINIT)
  6. #include <sys/types.h>
  7. #include <netinet/in.h>
  8. #include <arpa/inet.h>
  9. #include <arpa/nameser.h>
  10. #include <resolv.h>
  11. #define RES_RETRY_ON_FAILURE
  12. #endif
  13. #include <stdlib.h>
  14. #include <ctime>
  15. #include "nsHostResolver.h"
  16. #include "nsError.h"
  17. #include "nsISupportsBase.h"
  18. #include "nsISupportsUtils.h"
  19. #include "nsAutoPtr.h"
  20. #include "nsPrintfCString.h"
  21. #include "prthread.h"
  22. #include "prerror.h"
  23. #include "prtime.h"
  24. #include "mozilla/Logging.h"
  25. #include "PLDHashTable.h"
  26. #include "plstr.h"
  27. #include "nsURLHelper.h"
  28. #include "nsThreadUtils.h"
  29. #include "GetAddrInfo.h"
  30. #include "mozilla/HashFunctions.h"
  31. #include "mozilla/TimeStamp.h"
  32. #include "mozilla/DebugOnly.h"
  33. #include "mozilla/Preferences.h"
  34. using namespace mozilla;
  35. using namespace mozilla::net;
  36. // None of our implementations expose a TTL for negative responses, so we use a
  37. // constant always.
  38. static const unsigned int NEGATIVE_RECORD_LIFETIME = 60;
  39. //----------------------------------------------------------------------------
  40. // Use a persistent thread pool in order to avoid spinning up new threads all the time.
  41. // In particular, thread creation results in a res_init() call from libc which is
  42. // quite expensive.
  43. //
  44. // The pool dynamically grows between 0 and MAX_RESOLVER_THREADS in size. New requests
  45. // go first to an idle thread. If that cannot be found and there are fewer than MAX_RESOLVER_THREADS
  46. // currently in the pool a new thread is created for high priority requests. If
  47. // the new request is at a lower priority a new thread will only be created if
  48. // there are fewer than HighThreadThreshold currently outstanding. If a thread cannot be
  49. // created or an idle thread located for the request it is queued.
  50. //
  51. // When the pool is greater than HighThreadThreshold in size a thread will be destroyed after
  52. // ShortIdleTimeoutSeconds of idle time. Smaller pools use LongIdleTimeoutSeconds for a
  53. // timeout period.
  54. #define HighThreadThreshold MAX_RESOLVER_THREADS_FOR_ANY_PRIORITY
  55. #define LongIdleTimeoutSeconds 300 // for threads 1 -> HighThreadThreshold
  56. #define ShortIdleTimeoutSeconds 60 // for threads HighThreadThreshold+1 -> MAX_RESOLVER_THREADS
  57. static_assert(HighThreadThreshold <= MAX_RESOLVER_THREADS,
  58. "High Thread Threshold should be less equal Maximum allowed thread");
  59. //----------------------------------------------------------------------------
  60. static LazyLogModule gHostResolverLog("nsHostResolver");
  61. #define LOG(args) MOZ_LOG(gHostResolverLog, mozilla::LogLevel::Debug, args)
  62. #define LOG_ENABLED() MOZ_LOG_TEST(gHostResolverLog, mozilla::LogLevel::Debug)
  63. #define LOG_HOST(host, interface) host, \
  64. (interface && interface[0] != '\0') ? " on interface " : "", \
  65. (interface && interface[0] != '\0') ? interface : ""
  66. //----------------------------------------------------------------------------
  67. static inline void
  68. MoveCList(PRCList &from, PRCList &to)
  69. {
  70. if (!PR_CLIST_IS_EMPTY(&from)) {
  71. to.next = from.next;
  72. to.prev = from.prev;
  73. to.next->prev = &to;
  74. to.prev->next = &to;
  75. PR_INIT_CLIST(&from);
  76. }
  77. }
  78. //----------------------------------------------------------------------------
  79. #if defined(RES_RETRY_ON_FAILURE)
  80. // this class represents the resolver state for a given thread. if we
  81. // encounter a lookup failure, then we can invoke the Reset method on an
  82. // instance of this class to reset the resolver (in case /etc/resolv.conf
  83. // for example changed). this is mainly an issue on GNU systems since glibc
  84. // only reads in /etc/resolv.conf once per thread. it may be an issue on
  85. // other systems as well.
  86. class nsResState
  87. {
  88. public:
  89. nsResState()
  90. // initialize mLastReset to the time when this object
  91. // is created. this means that a reset will not occur
  92. // if a thread is too young. the alternative would be
  93. // to initialize this to the beginning of time, so that
  94. // the first failure would cause a reset, but since the
  95. // thread would have just started up, it likely would
  96. // already have current /etc/resolv.conf info.
  97. : mLastReset(PR_IntervalNow())
  98. {
  99. }
  100. bool Reset()
  101. {
  102. // reset no more than once per second
  103. if (PR_IntervalToSeconds(PR_IntervalNow() - mLastReset) < 1)
  104. return false;
  105. LOG(("Calling 'res_ninit'.\n"));
  106. mLastReset = PR_IntervalNow();
  107. return (res_ninit(&_res) == 0);
  108. }
  109. private:
  110. PRIntervalTime mLastReset;
  111. };
  112. #endif // RES_RETRY_ON_FAILURE
  113. //----------------------------------------------------------------------------
  114. static inline bool
  115. IsHighPriority(uint16_t flags)
  116. {
  117. return !(flags & (nsHostResolver::RES_PRIORITY_LOW | nsHostResolver::RES_PRIORITY_MEDIUM));
  118. }
  119. static inline bool
  120. IsMediumPriority(uint16_t flags)
  121. {
  122. return flags & nsHostResolver::RES_PRIORITY_MEDIUM;
  123. }
  124. static inline bool
  125. IsLowPriority(uint16_t flags)
  126. {
  127. return flags & nsHostResolver::RES_PRIORITY_LOW;
  128. }
  129. //----------------------------------------------------------------------------
  130. // this macro filters out any flags that are not used when constructing the
  131. // host key. the significant flags are those that would affect the resulting
  132. // host record (i.e., the flags that are passed down to PR_GetAddrInfoByName).
  133. #define RES_KEY_FLAGS(_f) ((_f) & nsHostResolver::RES_CANON_NAME)
  134. nsHostRecord::nsHostRecord(const nsHostKey *key)
  135. : addr_info_lock("nsHostRecord.addr_info_lock")
  136. , addr_info_gencnt(0)
  137. , addr_info(nullptr)
  138. , addr(nullptr)
  139. , negative(false)
  140. , resolving(false)
  141. , onQueue(false)
  142. , usingAnyThread(false)
  143. , mDoomed(false)
  144. #if TTL_AVAILABLE
  145. , mGetTtl(false)
  146. #endif
  147. , mBlacklistedCount(0)
  148. , mResolveAgain(false)
  149. {
  150. host = ((char *) this) + sizeof(nsHostRecord);
  151. memcpy((char *) host, key->host, strlen(key->host) + 1);
  152. flags = key->flags;
  153. af = key->af;
  154. netInterface = host + strlen(key->host) + 1;
  155. memcpy((char *) netInterface, key->netInterface,
  156. strlen(key->netInterface) + 1);
  157. PR_INIT_CLIST(this);
  158. PR_INIT_CLIST(&callbacks);
  159. }
  160. nsresult
  161. nsHostRecord::Create(const nsHostKey *key, nsHostRecord **result)
  162. {
  163. size_t hostLen = strlen(key->host) + 1;
  164. size_t netInterfaceLen = strlen(key->netInterface) + 1;
  165. size_t size = hostLen + netInterfaceLen + sizeof(nsHostRecord);
  166. // Use placement new to create the object with room for the hostname and
  167. // network interface name allocated after it.
  168. void *place = ::operator new(size);
  169. *result = new(place) nsHostRecord(key);
  170. NS_ADDREF(*result);
  171. return NS_OK;
  172. }
  173. void
  174. nsHostRecord::SetExpiration(const mozilla::TimeStamp& now, unsigned int valid, unsigned int grace)
  175. {
  176. mValidStart = now;
  177. mGraceStart = now + TimeDuration::FromSeconds(valid);
  178. mValidEnd = now + TimeDuration::FromSeconds(valid + grace);
  179. }
  180. void
  181. nsHostRecord::CopyExpirationTimesAndFlagsFrom(const nsHostRecord *aFromHostRecord)
  182. {
  183. // This is used to copy information from a cache entry to a record. All
  184. // information necessary for HasUsableRecord needs to be copied.
  185. mValidStart = aFromHostRecord->mValidStart;
  186. mValidEnd = aFromHostRecord->mValidEnd;
  187. mGraceStart = aFromHostRecord->mGraceStart;
  188. mDoomed = aFromHostRecord->mDoomed;
  189. }
  190. nsHostRecord::~nsHostRecord()
  191. {
  192. delete addr_info;
  193. delete addr;
  194. }
  195. bool
  196. nsHostRecord::Blacklisted(NetAddr *aQuery)
  197. {
  198. // must call locked
  199. LOG(("Checking blacklist for host [%s%s%s], host record [%p].\n",
  200. LOG_HOST(host, netInterface), this));
  201. // skip the string conversion for the common case of no blacklist
  202. if (!mBlacklistedItems.Length()) {
  203. return false;
  204. }
  205. char buf[kIPv6CStrBufSize];
  206. if (!NetAddrToString(aQuery, buf, sizeof(buf))) {
  207. return false;
  208. }
  209. nsDependentCString strQuery(buf);
  210. for (uint32_t i = 0; i < mBlacklistedItems.Length(); i++) {
  211. if (mBlacklistedItems.ElementAt(i).Equals(strQuery)) {
  212. LOG(("Address [%s] is blacklisted for host [%s%s%s].\n", buf,
  213. LOG_HOST(host, netInterface)));
  214. return true;
  215. }
  216. }
  217. return false;
  218. }
  219. void
  220. nsHostRecord::ReportUnusable(NetAddr *aAddress)
  221. {
  222. // must call locked
  223. LOG(("Adding address to blacklist for host [%s%s%s], host record [%p].\n",
  224. LOG_HOST(host, netInterface), this));
  225. ++mBlacklistedCount;
  226. if (negative)
  227. mDoomed = true;
  228. char buf[kIPv6CStrBufSize];
  229. if (NetAddrToString(aAddress, buf, sizeof(buf))) {
  230. LOG(("Successfully adding address [%s] to blacklist for host "
  231. "[%s%s%s].\n", buf, LOG_HOST(host, netInterface)));
  232. mBlacklistedItems.AppendElement(nsCString(buf));
  233. }
  234. }
  235. void
  236. nsHostRecord::ResetBlacklist()
  237. {
  238. // must call locked
  239. LOG(("Resetting blacklist for host [%s%s%s], host record [%p].\n",
  240. LOG_HOST(host, netInterface), this));
  241. mBlacklistedItems.Clear();
  242. }
  243. nsHostRecord::ExpirationStatus
  244. nsHostRecord::CheckExpiration(const mozilla::TimeStamp& now) const {
  245. if (!mGraceStart.IsNull() && now >= mGraceStart
  246. && !mValidEnd.IsNull() && now < mValidEnd) {
  247. return nsHostRecord::EXP_GRACE;
  248. } else if (!mValidEnd.IsNull() && now < mValidEnd) {
  249. return nsHostRecord::EXP_VALID;
  250. }
  251. return nsHostRecord::EXP_EXPIRED;
  252. }
  253. bool
  254. nsHostRecord::HasUsableResult(const mozilla::TimeStamp& now, uint16_t queryFlags) const
  255. {
  256. if (mDoomed) {
  257. return false;
  258. }
  259. // don't use cached negative results for high priority queries.
  260. if (negative && IsHighPriority(queryFlags)) {
  261. return false;
  262. }
  263. if (CheckExpiration(now) == EXP_EXPIRED) {
  264. return false;
  265. }
  266. return addr_info || addr || negative;
  267. }
  268. static size_t
  269. SizeOfResolveHostCallbackListExcludingHead(const PRCList *head,
  270. MallocSizeOf mallocSizeOf)
  271. {
  272. size_t n = 0;
  273. PRCList *curr = head->next;
  274. while (curr != head) {
  275. nsResolveHostCallback *callback =
  276. static_cast<nsResolveHostCallback*>(curr);
  277. n += callback->SizeOfIncludingThis(mallocSizeOf);
  278. curr = curr->next;
  279. }
  280. return n;
  281. }
  282. size_t
  283. nsHostRecord::SizeOfIncludingThis(MallocSizeOf mallocSizeOf) const
  284. {
  285. size_t n = mallocSizeOf(this);
  286. // The |host| field (inherited from nsHostKey) actually points to extra
  287. // memory that is allocated beyond the end of the nsHostRecord (see
  288. // nsHostRecord::Create()). So it will be included in the
  289. // |mallocSizeOf(this)| call above.
  290. n += SizeOfResolveHostCallbackListExcludingHead(&callbacks, mallocSizeOf);
  291. n += addr_info ? addr_info->SizeOfIncludingThis(mallocSizeOf) : 0;
  292. n += mallocSizeOf(addr);
  293. n += mBlacklistedItems.ShallowSizeOfExcludingThis(mallocSizeOf);
  294. for (size_t i = 0; i < mBlacklistedItems.Length(); i++) {
  295. n += mBlacklistedItems[i].SizeOfExcludingThisIfUnshared(mallocSizeOf);
  296. }
  297. return n;
  298. }
  299. nsHostRecord::DnsPriority
  300. nsHostRecord::GetPriority(uint16_t aFlags)
  301. {
  302. if (IsHighPriority(aFlags)){
  303. return nsHostRecord::DNS_PRIORITY_HIGH;
  304. } else if (IsMediumPriority(aFlags)) {
  305. return nsHostRecord::DNS_PRIORITY_MEDIUM;
  306. }
  307. return nsHostRecord::DNS_PRIORITY_LOW;
  308. }
  309. // Returns true if the entry can be removed, or false if it should be left.
  310. // Sets mResolveAgain true for entries being resolved right now.
  311. bool
  312. nsHostRecord::RemoveOrRefresh()
  313. {
  314. if (resolving) {
  315. if (!onQueue) {
  316. // The request has been passed to the OS resolver. The resultant DNS
  317. // record should be considered stale and not trusted; set a flag to
  318. // ensure it is called again.
  319. mResolveAgain = true;
  320. }
  321. // if Onqueue is true, the host entry is already added to the cache
  322. // but is still pending to get resolved: just leave it in hash.
  323. return false;
  324. }
  325. // Already resolved; not in a pending state; remove from cache.
  326. return true;
  327. }
  328. //----------------------------------------------------------------------------
  329. struct nsHostDBEnt : PLDHashEntryHdr
  330. {
  331. nsHostRecord *rec;
  332. };
  333. static PLDHashNumber
  334. HostDB_HashKey(const void *key)
  335. {
  336. const nsHostKey *hk = static_cast<const nsHostKey *>(key);
  337. return AddToHash(HashString(hk->host), RES_KEY_FLAGS(hk->flags), hk->af,
  338. HashString(hk->netInterface));
  339. }
  340. static bool
  341. HostDB_MatchEntry(const PLDHashEntryHdr *entry,
  342. const void *key)
  343. {
  344. const nsHostDBEnt *he = static_cast<const nsHostDBEnt *>(entry);
  345. const nsHostKey *hk = static_cast<const nsHostKey *>(key);
  346. return !strcmp(he->rec->host ? he->rec->host : "",
  347. hk->host ? hk->host : "") &&
  348. RES_KEY_FLAGS (he->rec->flags) == RES_KEY_FLAGS(hk->flags) &&
  349. he->rec->af == hk->af &&
  350. !strcmp(he->rec->netInterface, hk->netInterface);
  351. }
  352. static void
  353. HostDB_MoveEntry(PLDHashTable *table,
  354. const PLDHashEntryHdr *from,
  355. PLDHashEntryHdr *to)
  356. {
  357. static_cast<nsHostDBEnt *>(to)->rec =
  358. static_cast<const nsHostDBEnt *>(from)->rec;
  359. }
  360. static void
  361. HostDB_ClearEntry(PLDHashTable *table,
  362. PLDHashEntryHdr *entry)
  363. {
  364. nsHostDBEnt *he = static_cast<nsHostDBEnt*>(entry);
  365. MOZ_ASSERT(he, "nsHostDBEnt is null!");
  366. nsHostRecord *hr = he->rec;
  367. MOZ_ASSERT(hr, "nsHostDBEnt has null host record!");
  368. LOG(("Clearing cache db entry for host [%s%s%s].\n",
  369. LOG_HOST(hr->host, hr->netInterface)));
  370. #if defined(DEBUG)
  371. {
  372. MutexAutoLock lock(hr->addr_info_lock);
  373. if (!hr->addr_info) {
  374. LOG(("No address info for host [%s%s%s].\n",
  375. LOG_HOST(hr->host, hr->netInterface)));
  376. } else {
  377. if (!hr->mValidEnd.IsNull()) {
  378. TimeDuration diff = hr->mValidEnd - TimeStamp::NowLoRes();
  379. LOG(("Record for host [%s%s%s] expires in %f seconds.\n",
  380. LOG_HOST(hr->host, hr->netInterface),
  381. diff.ToSeconds()));
  382. } else {
  383. LOG(("Record for host [%s%s%s] not yet valid.\n",
  384. LOG_HOST(hr->host, hr->netInterface)));
  385. }
  386. NetAddrElement *addrElement = nullptr;
  387. char buf[kIPv6CStrBufSize];
  388. do {
  389. if (!addrElement) {
  390. addrElement = hr->addr_info->mAddresses.getFirst();
  391. } else {
  392. addrElement = addrElement->getNext();
  393. }
  394. if (addrElement) {
  395. NetAddrToString(&addrElement->mAddress, buf, sizeof(buf));
  396. LOG((" [%s]\n", buf));
  397. }
  398. }
  399. while (addrElement);
  400. }
  401. }
  402. #endif
  403. NS_RELEASE(he->rec);
  404. }
  405. static void
  406. HostDB_InitEntry(PLDHashEntryHdr *entry,
  407. const void *key)
  408. {
  409. nsHostDBEnt *he = static_cast<nsHostDBEnt *>(entry);
  410. nsHostRecord::Create(static_cast<const nsHostKey *>(key), &he->rec);
  411. }
  412. static const PLDHashTableOps gHostDB_ops =
  413. {
  414. HostDB_HashKey,
  415. HostDB_MatchEntry,
  416. HostDB_MoveEntry,
  417. HostDB_ClearEntry,
  418. HostDB_InitEntry,
  419. };
  420. //----------------------------------------------------------------------------
  421. #if TTL_AVAILABLE
  422. static const char kPrefGetTtl[] = "network.dns.get-ttl";
  423. static bool sGetTtlEnabled = false;
  424. static void DnsPrefChanged(const char* aPref, void* aClosure)
  425. {
  426. MOZ_ASSERT(NS_IsMainThread(),
  427. "Should be getting pref changed notification on main thread!");
  428. if (strcmp(aPref, kPrefGetTtl) != 0) {
  429. LOG(("DnsPrefChanged ignoring pref \"%s\"", aPref));
  430. return;
  431. }
  432. auto self = static_cast<nsHostResolver*>(aClosure);
  433. MOZ_ASSERT(self);
  434. sGetTtlEnabled = Preferences::GetBool(kPrefGetTtl);
  435. }
  436. #endif
  437. nsHostResolver::nsHostResolver(uint32_t maxCacheEntries,
  438. uint32_t defaultCacheEntryLifetime,
  439. uint32_t defaultGracePeriod)
  440. : mMaxCacheEntries(maxCacheEntries)
  441. , mDefaultCacheLifetime(defaultCacheEntryLifetime)
  442. , mDefaultGracePeriod(defaultGracePeriod)
  443. , mLock("nsHostResolver.mLock")
  444. , mIdleThreadCV(mLock, "nsHostResolver.mIdleThreadCV")
  445. , mDB(&gHostDB_ops, sizeof(nsHostDBEnt), 0)
  446. , mEvictionQSize(0)
  447. , mShutdown(true)
  448. , mNumIdleThreads(0)
  449. , mThreadCount(0)
  450. , mActiveAnyThreadCount(0)
  451. , mPendingCount(0)
  452. {
  453. mCreationTime = PR_Now();
  454. PR_INIT_CLIST(&mHighQ);
  455. PR_INIT_CLIST(&mMediumQ);
  456. PR_INIT_CLIST(&mLowQ);
  457. PR_INIT_CLIST(&mEvictionQ);
  458. mLongIdleTimeout = PR_SecondsToInterval(LongIdleTimeoutSeconds);
  459. mShortIdleTimeout = PR_SecondsToInterval(ShortIdleTimeoutSeconds);
  460. }
  461. nsHostResolver::~nsHostResolver() = default;
  462. nsresult
  463. nsHostResolver::Init()
  464. {
  465. if (NS_FAILED(GetAddrInfoInit())) {
  466. return NS_ERROR_FAILURE;
  467. }
  468. mShutdown = false;
  469. #if TTL_AVAILABLE
  470. // The preferences probably haven't been loaded from the disk yet, so we
  471. // need to register a callback that will set up the experiment once they
  472. // are. We also need to explicitly set a value for the props otherwise the
  473. // callback won't be called.
  474. {
  475. DebugOnly<nsresult> rv = Preferences::RegisterCallbackAndCall(
  476. &DnsPrefChanged, kPrefGetTtl, this);
  477. NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
  478. "Could not register DNS TTL pref callback.");
  479. }
  480. #endif
  481. #if defined(HAVE_RES_NINIT)
  482. // We want to make sure the system is using the correct resolver settings,
  483. // so we force it to reload those settings whenever we startup a subsequent
  484. // nsHostResolver instance. We assume that there is no reason to do this
  485. // for the first nsHostResolver instance since that is usually created
  486. // during application startup.
  487. static int initCount = 0;
  488. if (initCount++ > 0) {
  489. LOG(("Calling 'res_ninit'.\n"));
  490. res_ninit(&_res);
  491. }
  492. #endif
  493. return NS_OK;
  494. }
  495. void
  496. nsHostResolver::ClearPendingQueue(PRCList *aPendingQ)
  497. {
  498. // loop through pending queue, erroring out pending lookups.
  499. if (!PR_CLIST_IS_EMPTY(aPendingQ)) {
  500. PRCList *node = aPendingQ->next;
  501. while (node != aPendingQ) {
  502. nsHostRecord *rec = static_cast<nsHostRecord *>(node);
  503. node = node->next;
  504. OnLookupComplete(rec, NS_ERROR_ABORT, nullptr);
  505. }
  506. }
  507. }
  508. //
  509. // FlushCache() is what we call when the network has changed. We must not
  510. // trust names that were resolved before this change. They may resolve
  511. // differently now.
  512. //
  513. // This function removes all existing resolved host entries from the hash.
  514. // Names that are in the pending queues can be left there. Entries in the
  515. // cache that have 'Resolve' set true but not 'onQueue' are being resolved
  516. // right now, so we need to mark them to get re-resolved on completion!
  517. void
  518. nsHostResolver::FlushCache()
  519. {
  520. MutexAutoLock lock(mLock);
  521. mEvictionQSize = 0;
  522. // Clear the evictionQ and remove all its corresponding entries from
  523. // the cache first
  524. if (!PR_CLIST_IS_EMPTY(&mEvictionQ)) {
  525. PRCList *node = mEvictionQ.next;
  526. while (node != &mEvictionQ) {
  527. nsHostRecord *rec = static_cast<nsHostRecord *>(node);
  528. node = node->next;
  529. PR_REMOVE_AND_INIT_LINK(rec);
  530. mDB.Remove((nsHostKey *) rec);
  531. NS_RELEASE(rec);
  532. }
  533. }
  534. // Refresh the cache entries that are resolving RIGHT now, remove the rest.
  535. for (auto iter = mDB.Iter(); !iter.Done(); iter.Next()) {
  536. auto entry = static_cast<nsHostDBEnt *>(iter.Get());
  537. // Try to remove the record, or mark it for refresh.
  538. if (entry->rec->RemoveOrRefresh()) {
  539. PR_REMOVE_LINK(entry->rec);
  540. iter.Remove();
  541. }
  542. }
  543. }
  544. void
  545. nsHostResolver::Shutdown()
  546. {
  547. LOG(("Shutting down host resolver.\n"));
  548. #if TTL_AVAILABLE
  549. {
  550. DebugOnly<nsresult> rv = Preferences::UnregisterCallback(
  551. &DnsPrefChanged, kPrefGetTtl, this);
  552. NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
  553. "Could not unregister DNS TTL pref callback.");
  554. }
  555. #endif
  556. PRCList pendingQHigh, pendingQMed, pendingQLow, evictionQ;
  557. PR_INIT_CLIST(&pendingQHigh);
  558. PR_INIT_CLIST(&pendingQMed);
  559. PR_INIT_CLIST(&pendingQLow);
  560. PR_INIT_CLIST(&evictionQ);
  561. {
  562. MutexAutoLock lock(mLock);
  563. mShutdown = true;
  564. MoveCList(mHighQ, pendingQHigh);
  565. MoveCList(mMediumQ, pendingQMed);
  566. MoveCList(mLowQ, pendingQLow);
  567. MoveCList(mEvictionQ, evictionQ);
  568. mEvictionQSize = 0;
  569. mPendingCount = 0;
  570. if (mNumIdleThreads)
  571. mIdleThreadCV.NotifyAll();
  572. // empty host database
  573. mDB.Clear();
  574. }
  575. ClearPendingQueue(&pendingQHigh);
  576. ClearPendingQueue(&pendingQMed);
  577. ClearPendingQueue(&pendingQLow);
  578. if (!PR_CLIST_IS_EMPTY(&evictionQ)) {
  579. PRCList *node = evictionQ.next;
  580. while (node != &evictionQ) {
  581. nsHostRecord *rec = static_cast<nsHostRecord *>(node);
  582. node = node->next;
  583. NS_RELEASE(rec);
  584. }
  585. }
  586. #ifdef NS_BUILD_REFCNT_LOGGING
  587. // Logically join the outstanding worker threads with a timeout.
  588. // Use this approach instead of PR_JoinThread() because that does
  589. // not allow a timeout which may be necessary for a semi-responsive
  590. // shutdown if the thread is blocked on a very slow DNS resolution.
  591. // mThreadCount is read outside of mLock, but the worst case
  592. // scenario for that race is one extra 25ms sleep.
  593. PRIntervalTime delay = PR_MillisecondsToInterval(25);
  594. PRIntervalTime stopTime = PR_IntervalNow() + PR_SecondsToInterval(20);
  595. while (mThreadCount && PR_IntervalNow() < stopTime)
  596. PR_Sleep(delay);
  597. #endif
  598. {
  599. mozilla::DebugOnly<nsresult> rv = GetAddrInfoShutdown();
  600. NS_WARNING_ASSERTION(NS_SUCCEEDED(rv),
  601. "Failed to shutdown GetAddrInfo");
  602. }
  603. }
  604. void
  605. nsHostResolver::MoveQueue(nsHostRecord *aRec, PRCList &aDestQ)
  606. {
  607. NS_ASSERTION(aRec->onQueue, "Moving Host Record Not Currently Queued");
  608. PR_REMOVE_LINK(aRec);
  609. PR_APPEND_LINK(aRec, &aDestQ);
  610. }
  611. nsresult
  612. nsHostResolver::ResolveHost(const char *host,
  613. uint16_t flags,
  614. uint16_t af,
  615. const char *netInterface,
  616. nsResolveHostCallback *callback)
  617. {
  618. NS_ENSURE_TRUE(host && *host, NS_ERROR_UNEXPECTED);
  619. NS_ENSURE_TRUE(netInterface, NS_ERROR_UNEXPECTED);
  620. LOG(("Resolving host [%s%s%s]%s.\n", LOG_HOST(host, netInterface),
  621. flags & RES_BYPASS_CACHE ? " - bypassing cache" : ""));
  622. // ensure that we are working with a valid hostname before proceeding. see
  623. // bug 304904 for details.
  624. if (!net_IsValidHostName(nsDependentCString(host)))
  625. return NS_ERROR_UNKNOWN_HOST;
  626. // if result is set inside the lock, then we need to issue the
  627. // callback before returning.
  628. RefPtr<nsHostRecord> result;
  629. nsresult status = NS_OK, rv = NS_OK;
  630. {
  631. MutexAutoLock lock(mLock);
  632. if (mShutdown)
  633. rv = NS_ERROR_NOT_INITIALIZED;
  634. else {
  635. // Used to try to parse to an IP address literal.
  636. PRNetAddr tempAddr;
  637. // Unfortunately, PR_StringToNetAddr does not properly initialize
  638. // the output buffer in the case of IPv6 input. See bug 223145.
  639. memset(&tempAddr, 0, sizeof(PRNetAddr));
  640. // check to see if there is already an entry for this |host|
  641. // in the hash table. if so, then check to see if we can't
  642. // just reuse the lookup result. otherwise, if there are
  643. // any pending callbacks, then add to pending callbacks queue,
  644. // and return. otherwise, add ourselves as first pending
  645. // callback, and proceed to do the lookup.
  646. nsHostKey key = { host, flags, af, netInterface };
  647. auto he = static_cast<nsHostDBEnt*>(mDB.Add(&key, fallible));
  648. // if the record is null, the hash table OOM'd.
  649. if (!he) {
  650. LOG((" Out of memory: no cache entry for host [%s%s%s].\n",
  651. LOG_HOST(host, netInterface)));
  652. rv = NS_ERROR_OUT_OF_MEMORY;
  653. }
  654. // do we have a cached result that we can reuse?
  655. else if (!(flags & RES_BYPASS_CACHE) &&
  656. he->rec->HasUsableResult(TimeStamp::NowLoRes(), flags)) {
  657. LOG((" Using cached record for host [%s%s%s].\n",
  658. LOG_HOST(host, netInterface)));
  659. // put reference to host record on stack...
  660. result = he->rec;
  661. // For entries that are in the grace period
  662. // or all cached negative entries, use the cache but start a new
  663. // lookup in the background
  664. ConditionallyRefreshRecord(he->rec, host);
  665. if (he->rec->negative) {
  666. LOG((" Negative cache entry for host [%s%s%s].\n",
  667. LOG_HOST(host, netInterface)));
  668. status = NS_ERROR_UNKNOWN_HOST;
  669. }
  670. }
  671. // if the host name is an IP address literal and has been parsed,
  672. // go ahead and use it.
  673. else if (he->rec->addr) {
  674. LOG((" Using cached address for IP Literal [%s].\n", host));
  675. result = he->rec;
  676. }
  677. // try parsing the host name as an IP address literal to short
  678. // circuit full host resolution. (this is necessary on some
  679. // platforms like Win9x. see bug 219376 for more details.)
  680. else if (PR_StringToNetAddr(host, &tempAddr) == PR_SUCCESS) {
  681. LOG((" Host is IP Literal [%s].\n", host));
  682. // ok, just copy the result into the host record, and be done
  683. // with it! ;-)
  684. he->rec->addr = new NetAddr();
  685. PRNetAddrToNetAddr(&tempAddr, he->rec->addr);
  686. // put reference to host record on stack...
  687. result = he->rec;
  688. }
  689. else if (mPendingCount >= MAX_NON_PRIORITY_REQUESTS &&
  690. !IsHighPriority(flags) &&
  691. !he->rec->resolving) {
  692. LOG((" Lookup queue full: dropping %s priority request for "
  693. "host [%s%s%s].\n",
  694. IsMediumPriority(flags) ? "medium" : "low",
  695. LOG_HOST(host, netInterface)));
  696. // This is a lower priority request and we are swamped, so refuse it.
  697. rv = NS_ERROR_DNS_LOOKUP_QUEUE_FULL;
  698. }
  699. else if (flags & RES_OFFLINE) {
  700. LOG((" Offline request for host [%s%s%s]; ignoring.\n",
  701. LOG_HOST(host, netInterface)));
  702. rv = NS_ERROR_OFFLINE;
  703. }
  704. // If this is an IPV4 or IPV6 specific request, check if there is
  705. // an AF_UNSPEC entry we can use. Otherwise, hit the resolver...
  706. else if (!he->rec->resolving) {
  707. if (!(flags & RES_BYPASS_CACHE) &&
  708. ((af == PR_AF_INET) || (af == PR_AF_INET6))) {
  709. // First, search for an entry with AF_UNSPEC
  710. const nsHostKey unspecKey = { host, flags, PR_AF_UNSPEC,
  711. netInterface };
  712. auto unspecHe =
  713. static_cast<nsHostDBEnt*>(mDB.Search(&unspecKey));
  714. NS_ASSERTION(!unspecHe ||
  715. (unspecHe && unspecHe->rec),
  716. "Valid host entries should contain a record");
  717. TimeStamp now = TimeStamp::NowLoRes();
  718. if (unspecHe &&
  719. unspecHe->rec->HasUsableResult(now, flags)) {
  720. MOZ_ASSERT(unspecHe->rec->addr_info || unspecHe->rec->negative,
  721. "Entry should be resolved or negative.");
  722. LOG((" Trying AF_UNSPEC entry for host [%s%s%s] af: %s.\n",
  723. LOG_HOST(host, netInterface),
  724. (af == PR_AF_INET) ? "AF_INET" : "AF_INET6"));
  725. he->rec->addr_info = nullptr;
  726. if (unspecHe->rec->negative) {
  727. he->rec->negative = unspecHe->rec->negative;
  728. he->rec->CopyExpirationTimesAndFlagsFrom(unspecHe->rec);
  729. } else if (unspecHe->rec->addr_info) {
  730. // Search for any valid address in the AF_UNSPEC entry
  731. // in the cache (not blacklisted and from the right
  732. // family).
  733. NetAddrElement *addrIter =
  734. unspecHe->rec->addr_info->mAddresses.getFirst();
  735. while (addrIter) {
  736. if ((af == addrIter->mAddress.inet.family) &&
  737. !unspecHe->rec->Blacklisted(&addrIter->mAddress)) {
  738. if (!he->rec->addr_info) {
  739. he->rec->addr_info = new AddrInfo(
  740. unspecHe->rec->addr_info->mHostName,
  741. unspecHe->rec->addr_info->mCanonicalName);
  742. he->rec->CopyExpirationTimesAndFlagsFrom(unspecHe->rec);
  743. }
  744. he->rec->addr_info->AddAddress(
  745. new NetAddrElement(*addrIter));
  746. }
  747. addrIter = addrIter->getNext();
  748. }
  749. }
  750. // Now check if we have a new record.
  751. if (he->rec->HasUsableResult(now, flags)) {
  752. result = he->rec;
  753. if (he->rec->negative) {
  754. status = NS_ERROR_UNKNOWN_HOST;
  755. }
  756. ConditionallyRefreshRecord(he->rec, host);
  757. }
  758. // For AF_INET6, a new lookup means another AF_UNSPEC
  759. // lookup. We have already iterated through the
  760. // AF_UNSPEC addresses, so we mark this record as
  761. // negative.
  762. else if (af == PR_AF_INET6) {
  763. LOG((" No AF_INET6 in AF_UNSPEC entry: "
  764. "host [%s%s%s] unknown host.",
  765. LOG_HOST(host, netInterface)));
  766. result = he->rec;
  767. he->rec->negative = true;
  768. status = NS_ERROR_UNKNOWN_HOST;
  769. }
  770. }
  771. }
  772. // If no valid address was found in the cache or this is an
  773. // AF_UNSPEC request, then start a new lookup.
  774. if (!result) {
  775. LOG((" No usable address in cache for host [%s%s%s].",
  776. LOG_HOST(host, netInterface)));
  777. // Add callback to the list of pending callbacks.
  778. PR_APPEND_LINK(callback, &he->rec->callbacks);
  779. he->rec->flags = flags;
  780. rv = IssueLookup(he->rec);
  781. if (NS_FAILED(rv)) {
  782. PR_REMOVE_AND_INIT_LINK(callback);
  783. }
  784. else {
  785. LOG((" DNS lookup for host [%s%s%s] blocking "
  786. "pending 'getaddrinfo' query: callback [%p]",
  787. LOG_HOST(host, netInterface), callback));
  788. }
  789. }
  790. }
  791. else {
  792. LOG((" Host [%s%s%s] is being resolved. Appending callback "
  793. "[%p].", LOG_HOST(host, netInterface), callback));
  794. PR_APPEND_LINK(callback, &he->rec->callbacks);
  795. if (he->rec->onQueue) {
  796. // Consider the case where we are on a pending queue of
  797. // lower priority than the request is being made at.
  798. // In that case we should upgrade to the higher queue.
  799. if (IsHighPriority(flags) &&
  800. !IsHighPriority(he->rec->flags)) {
  801. // Move from (low|med) to high.
  802. MoveQueue(he->rec, mHighQ);
  803. he->rec->flags = flags;
  804. ConditionallyCreateThread(he->rec);
  805. } else if (IsMediumPriority(flags) &&
  806. IsLowPriority(he->rec->flags)) {
  807. // Move from low to med.
  808. MoveQueue(he->rec, mMediumQ);
  809. he->rec->flags = flags;
  810. mIdleThreadCV.Notify();
  811. }
  812. }
  813. }
  814. }
  815. }
  816. if (result) {
  817. callback->OnLookupComplete(this, result, status);
  818. }
  819. return rv;
  820. }
  821. void
  822. nsHostResolver::DetachCallback(const char *host,
  823. uint16_t flags,
  824. uint16_t af,
  825. const char *netInterface,
  826. nsResolveHostCallback *callback,
  827. nsresult status)
  828. {
  829. RefPtr<nsHostRecord> rec;
  830. {
  831. MutexAutoLock lock(mLock);
  832. nsHostKey key = { host, flags, af, netInterface };
  833. auto he = static_cast<nsHostDBEnt*>(mDB.Search(&key));
  834. if (he) {
  835. // walk list looking for |callback|... we cannot assume
  836. // that it will be there!
  837. PRCList *node = he->rec->callbacks.next;
  838. while (node != &he->rec->callbacks) {
  839. if (static_cast<nsResolveHostCallback *>(node) == callback) {
  840. PR_REMOVE_LINK(callback);
  841. rec = he->rec;
  842. break;
  843. }
  844. node = node->next;
  845. }
  846. }
  847. }
  848. // complete callback with the given status code; this would only be done if
  849. // the record was in the process of being resolved.
  850. if (rec)
  851. callback->OnLookupComplete(this, rec, status);
  852. }
  853. nsresult
  854. nsHostResolver::ConditionallyCreateThread(nsHostRecord *rec)
  855. {
  856. if (mNumIdleThreads) {
  857. // wake up idle thread to process this lookup
  858. mIdleThreadCV.Notify();
  859. }
  860. else if ((mThreadCount < HighThreadThreshold) ||
  861. (IsHighPriority(rec->flags) && mThreadCount < MAX_RESOLVER_THREADS)) {
  862. // dispatch new worker thread
  863. NS_ADDREF_THIS(); // owning reference passed to thread
  864. mThreadCount++;
  865. PRThread *thr = PR_CreateThread(PR_SYSTEM_THREAD,
  866. ThreadFunc,
  867. this,
  868. PR_PRIORITY_NORMAL,
  869. PR_GLOBAL_THREAD,
  870. PR_UNJOINABLE_THREAD,
  871. 0);
  872. if (!thr) {
  873. mThreadCount--;
  874. NS_RELEASE_THIS();
  875. return NS_ERROR_OUT_OF_MEMORY;
  876. }
  877. }
  878. else {
  879. LOG((" Unable to find a thread for looking up host [%s%s%s].\n",
  880. LOG_HOST(rec->host, rec->netInterface)));
  881. }
  882. return NS_OK;
  883. }
  884. nsresult
  885. nsHostResolver::IssueLookup(nsHostRecord *rec)
  886. {
  887. nsresult rv = NS_OK;
  888. NS_ASSERTION(!rec->resolving, "record is already being resolved");
  889. // Add rec to one of the pending queues, possibly removing it from mEvictionQ.
  890. // If rec is on mEvictionQ, then we can just move the owning
  891. // reference over to the new active queue.
  892. if (rec->next == rec)
  893. NS_ADDREF(rec);
  894. else {
  895. PR_REMOVE_LINK(rec);
  896. mEvictionQSize--;
  897. }
  898. switch (nsHostRecord::GetPriority(rec->flags)) {
  899. case nsHostRecord::DNS_PRIORITY_HIGH:
  900. PR_APPEND_LINK(rec, &mHighQ);
  901. break;
  902. case nsHostRecord::DNS_PRIORITY_MEDIUM:
  903. PR_APPEND_LINK(rec, &mMediumQ);
  904. break;
  905. case nsHostRecord::DNS_PRIORITY_LOW:
  906. PR_APPEND_LINK(rec, &mLowQ);
  907. break;
  908. }
  909. mPendingCount++;
  910. rec->resolving = true;
  911. rec->onQueue = true;
  912. rv = ConditionallyCreateThread(rec);
  913. LOG ((" DNS thread counters: total=%d any-live=%d idle=%d pending=%d\n",
  914. static_cast<uint32_t>(mThreadCount),
  915. static_cast<uint32_t>(mActiveAnyThreadCount),
  916. static_cast<uint32_t>(mNumIdleThreads),
  917. static_cast<uint32_t>(mPendingCount)));
  918. return rv;
  919. }
  920. nsresult
  921. nsHostResolver::ConditionallyRefreshRecord(nsHostRecord *rec, const char *host)
  922. {
  923. if ((rec->CheckExpiration(TimeStamp::NowLoRes()) != nsHostRecord::EXP_VALID
  924. || rec->negative) && !rec->resolving) {
  925. LOG((" Using %s cache entry for host [%s] but starting async renewal.",
  926. rec->negative ? "negative" :"positive", host));
  927. IssueLookup(rec);
  928. }
  929. return NS_OK;
  930. }
  931. void
  932. nsHostResolver::DeQueue(PRCList &aQ, nsHostRecord **aResult)
  933. {
  934. *aResult = static_cast<nsHostRecord *>(aQ.next);
  935. PR_REMOVE_AND_INIT_LINK(*aResult);
  936. mPendingCount--;
  937. (*aResult)->onQueue = false;
  938. }
  939. bool
  940. nsHostResolver::GetHostToLookup(nsHostRecord **result)
  941. {
  942. bool timedOut = false;
  943. PRIntervalTime epoch, now, timeout;
  944. MutexAutoLock lock(mLock);
  945. timeout = (mNumIdleThreads >= HighThreadThreshold) ? mShortIdleTimeout : mLongIdleTimeout;
  946. epoch = PR_IntervalNow();
  947. while (!mShutdown) {
  948. // remove next record from Q; hand over owning reference. Check high, then med, then low
  949. #if TTL_AVAILABLE
  950. #define SET_GET_TTL(var, val) \
  951. (var)->mGetTtl = sGetTtlEnabled && (val)
  952. #else
  953. #define SET_GET_TTL(var, val)
  954. #endif
  955. if (!PR_CLIST_IS_EMPTY(&mHighQ)) {
  956. DeQueue (mHighQ, result);
  957. SET_GET_TTL(*result, false);
  958. return true;
  959. }
  960. if (mActiveAnyThreadCount < HighThreadThreshold) {
  961. if (!PR_CLIST_IS_EMPTY(&mMediumQ)) {
  962. DeQueue (mMediumQ, result);
  963. mActiveAnyThreadCount++;
  964. (*result)->usingAnyThread = true;
  965. SET_GET_TTL(*result, true);
  966. return true;
  967. }
  968. if (!PR_CLIST_IS_EMPTY(&mLowQ)) {
  969. DeQueue (mLowQ, result);
  970. mActiveAnyThreadCount++;
  971. (*result)->usingAnyThread = true;
  972. SET_GET_TTL(*result, true);
  973. return true;
  974. }
  975. }
  976. // Determining timeout is racy, so allow one cycle through checking the queues
  977. // before exiting.
  978. if (timedOut)
  979. break;
  980. // wait for one or more of the following to occur:
  981. // (1) the pending queue has a host record to process
  982. // (2) the shutdown flag has been set
  983. // (3) the thread has been idle for too long
  984. mNumIdleThreads++;
  985. mIdleThreadCV.Wait(timeout);
  986. mNumIdleThreads--;
  987. now = PR_IntervalNow();
  988. if ((PRIntervalTime)(now - epoch) >= timeout)
  989. timedOut = true;
  990. else {
  991. // It is possible that PR_WaitCondVar() was interrupted and returned early,
  992. // in which case we will loop back and re-enter it. In that case we want to
  993. // do so with the new timeout reduced to reflect time already spent waiting.
  994. timeout -= (PRIntervalTime)(now - epoch);
  995. epoch = now;
  996. }
  997. }
  998. // tell thread to exit...
  999. return false;
  1000. }
  1001. void
  1002. nsHostResolver::PrepareRecordExpiration(nsHostRecord* rec) const
  1003. {
  1004. MOZ_ASSERT(((bool)rec->addr_info) != rec->negative);
  1005. if (!rec->addr_info) {
  1006. rec->SetExpiration(TimeStamp::NowLoRes(),
  1007. NEGATIVE_RECORD_LIFETIME, 0);
  1008. LOG(("Caching host [%s%s%s] negative record for %u seconds.\n",
  1009. LOG_HOST(rec->host, rec->netInterface),
  1010. NEGATIVE_RECORD_LIFETIME));
  1011. return;
  1012. }
  1013. unsigned int lifetime = mDefaultCacheLifetime;
  1014. unsigned int grace = mDefaultGracePeriod;
  1015. #if TTL_AVAILABLE
  1016. unsigned int ttl = mDefaultCacheLifetime;
  1017. if (sGetTtlEnabled) {
  1018. MutexAutoLock lock(rec->addr_info_lock);
  1019. if (rec->addr_info && rec->addr_info->ttl != AddrInfo::NO_TTL_DATA) {
  1020. ttl = rec->addr_info->ttl;
  1021. }
  1022. lifetime = ttl;
  1023. grace = 0;
  1024. }
  1025. #endif
  1026. rec->SetExpiration(TimeStamp::NowLoRes(), lifetime, grace);
  1027. LOG(("Caching host [%s%s%s] record for %u seconds (grace %d).",
  1028. LOG_HOST(rec->host, rec->netInterface), lifetime, grace));
  1029. }
  1030. static bool
  1031. different_rrset(AddrInfo *rrset1, AddrInfo *rrset2)
  1032. {
  1033. if (!rrset1 || !rrset2) {
  1034. return true;
  1035. }
  1036. LOG(("different_rrset %s\n", rrset1->mHostName));
  1037. nsTArray<NetAddr> orderedSet1;
  1038. nsTArray<NetAddr> orderedSet2;
  1039. for (NetAddrElement *element = rrset1->mAddresses.getFirst();
  1040. element; element = element->getNext()) {
  1041. if (LOG_ENABLED()) {
  1042. char buf[128];
  1043. NetAddrToString(&element->mAddress, buf, 128);
  1044. LOG(("different_rrset add to set 1 %s\n", buf));
  1045. }
  1046. orderedSet1.InsertElementAt(orderedSet1.Length(), element->mAddress);
  1047. }
  1048. for (NetAddrElement *element = rrset2->mAddresses.getFirst();
  1049. element; element = element->getNext()) {
  1050. if (LOG_ENABLED()) {
  1051. char buf[128];
  1052. NetAddrToString(&element->mAddress, buf, 128);
  1053. LOG(("different_rrset add to set 2 %s\n", buf));
  1054. }
  1055. orderedSet2.InsertElementAt(orderedSet2.Length(), element->mAddress);
  1056. }
  1057. if (orderedSet1.Length() != orderedSet2.Length()) {
  1058. LOG(("different_rrset true due to length change\n"));
  1059. return true;
  1060. }
  1061. orderedSet1.Sort();
  1062. orderedSet2.Sort();
  1063. for (uint32_t i = 0; i < orderedSet1.Length(); ++i) {
  1064. if (!(orderedSet1[i] == orderedSet2[i])) {
  1065. LOG(("different_rrset true due to content change\n"));
  1066. return true;
  1067. }
  1068. }
  1069. LOG(("different_rrset false\n"));
  1070. return false;
  1071. }
  1072. //
  1073. // OnLookupComplete() checks if the resolving should be redone and if so it
  1074. // returns LOOKUP_RESOLVEAGAIN, but only if 'status' is not NS_ERROR_ABORT.
  1075. // takes ownership of AddrInfo parameter
  1076. nsHostResolver::LookupStatus
  1077. nsHostResolver::OnLookupComplete(nsHostRecord* rec, nsresult status, AddrInfo* newRRSet)
  1078. {
  1079. // get the list of pending callbacks for this lookup, and notify
  1080. // them that the lookup is complete.
  1081. PRCList cbs;
  1082. PR_INIT_CLIST(&cbs);
  1083. {
  1084. MutexAutoLock lock(mLock);
  1085. if (rec->mResolveAgain && (status != NS_ERROR_ABORT)) {
  1086. LOG(("nsHostResolver record %p resolve again due to flushcache\n", rec));
  1087. rec->mResolveAgain = false;
  1088. delete newRRSet;
  1089. return LOOKUP_RESOLVEAGAIN;
  1090. }
  1091. // grab list of callbacks to notify
  1092. MoveCList(rec->callbacks, cbs);
  1093. // update record fields. We might have a rec->addr_info already if a
  1094. // previous lookup result expired and we're reresolving it..
  1095. AddrInfo *old_addr_info;
  1096. {
  1097. MutexAutoLock lock(rec->addr_info_lock);
  1098. if (different_rrset(rec->addr_info, newRRSet)) {
  1099. LOG(("nsHostResolver record %p new gencnt\n", rec));
  1100. old_addr_info = rec->addr_info;
  1101. rec->addr_info = newRRSet;
  1102. rec->addr_info_gencnt++;
  1103. } else {
  1104. if (rec->addr_info && newRRSet) {
  1105. rec->addr_info->ttl = newRRSet->ttl;
  1106. }
  1107. old_addr_info = newRRSet;
  1108. }
  1109. }
  1110. delete old_addr_info;
  1111. rec->negative = !rec->addr_info;
  1112. PrepareRecordExpiration(rec);
  1113. rec->resolving = false;
  1114. if (rec->usingAnyThread) {
  1115. mActiveAnyThreadCount--;
  1116. rec->usingAnyThread = false;
  1117. }
  1118. if (!mShutdown) {
  1119. // add to mEvictionQ
  1120. PR_APPEND_LINK(rec, &mEvictionQ);
  1121. NS_ADDREF(rec);
  1122. if (mEvictionQSize < mMaxCacheEntries)
  1123. mEvictionQSize++;
  1124. else {
  1125. // remove first element on mEvictionQ
  1126. nsHostRecord *head =
  1127. static_cast<nsHostRecord *>(PR_LIST_HEAD(&mEvictionQ));
  1128. PR_REMOVE_AND_INIT_LINK(head);
  1129. mDB.Remove((nsHostKey *) head);
  1130. // release reference to rec owned by mEvictionQ
  1131. NS_RELEASE(head);
  1132. }
  1133. #if TTL_AVAILABLE
  1134. if (!rec->mGetTtl && !rec->resolving && sGetTtlEnabled) {
  1135. LOG(("Issuing second async lookup for TTL for host [%s%s%s].",
  1136. LOG_HOST(rec->host, rec->netInterface)));
  1137. rec->flags =
  1138. (rec->flags & ~RES_PRIORITY_MEDIUM) | RES_PRIORITY_LOW;
  1139. DebugOnly<nsresult> rv = IssueLookup(rec);
  1140. NS_WARNING_ASSERTION(
  1141. NS_SUCCEEDED(rv),
  1142. "Could not issue second async lookup for TTL.");
  1143. }
  1144. #endif
  1145. }
  1146. }
  1147. if (!PR_CLIST_IS_EMPTY(&cbs)) {
  1148. PRCList *node = cbs.next;
  1149. while (node != &cbs) {
  1150. nsResolveHostCallback *callback =
  1151. static_cast<nsResolveHostCallback *>(node);
  1152. node = node->next;
  1153. callback->OnLookupComplete(this, rec, status);
  1154. // NOTE: callback must not be dereferenced after this point!!
  1155. }
  1156. }
  1157. NS_RELEASE(rec);
  1158. return LOOKUP_OK;
  1159. }
  1160. void
  1161. nsHostResolver::CancelAsyncRequest(const char *host,
  1162. uint16_t flags,
  1163. uint16_t af,
  1164. const char *netInterface,
  1165. nsIDNSListener *aListener,
  1166. nsresult status)
  1167. {
  1168. MutexAutoLock lock(mLock);
  1169. // Lookup the host record associated with host, flags & address family
  1170. nsHostKey key = { host, flags, af, netInterface };
  1171. auto he = static_cast<nsHostDBEnt*>(mDB.Search(&key));
  1172. if (he) {
  1173. nsHostRecord* recPtr = nullptr;
  1174. PRCList *node = he->rec->callbacks.next;
  1175. // Remove the first nsDNSAsyncRequest callback which matches the
  1176. // supplied listener object
  1177. while (node != &he->rec->callbacks) {
  1178. nsResolveHostCallback *callback
  1179. = static_cast<nsResolveHostCallback *>(node);
  1180. if (callback && (callback->EqualsAsyncListener(aListener))) {
  1181. // Remove from the list of callbacks
  1182. PR_REMOVE_LINK(callback);
  1183. recPtr = he->rec;
  1184. callback->OnLookupComplete(this, recPtr, status);
  1185. break;
  1186. }
  1187. node = node->next;
  1188. }
  1189. // If there are no more callbacks, remove the hash table entry
  1190. if (recPtr && PR_CLIST_IS_EMPTY(&recPtr->callbacks)) {
  1191. mDB.Remove((nsHostKey *)recPtr);
  1192. // If record is on a Queue, remove it and then deref it
  1193. if (recPtr->next != recPtr) {
  1194. PR_REMOVE_LINK(recPtr);
  1195. NS_RELEASE(recPtr);
  1196. }
  1197. }
  1198. }
  1199. }
  1200. size_t
  1201. nsHostResolver::SizeOfIncludingThis(MallocSizeOf mallocSizeOf) const
  1202. {
  1203. MutexAutoLock lock(mLock);
  1204. size_t n = mallocSizeOf(this);
  1205. n += mDB.ShallowSizeOfExcludingThis(mallocSizeOf);
  1206. for (auto iter = mDB.ConstIter(); !iter.Done(); iter.Next()) {
  1207. auto entry = static_cast<nsHostDBEnt*>(iter.Get());
  1208. n += entry->rec->SizeOfIncludingThis(mallocSizeOf);
  1209. }
  1210. // The following fields aren't measured.
  1211. // - mHighQ, mMediumQ, mLowQ, mEvictionQ, because they just point to
  1212. // nsHostRecords that also pointed to by entries |mDB|, and measured when
  1213. // |mDB| is measured.
  1214. return n;
  1215. }
  1216. void
  1217. nsHostResolver::ThreadFunc(void *arg)
  1218. {
  1219. LOG(("DNS lookup thread - starting execution.\n"));
  1220. static nsThreadPoolNaming naming;
  1221. naming.SetThreadPoolName(NS_LITERAL_CSTRING("DNS Resolver"));
  1222. #if defined(RES_RETRY_ON_FAILURE)
  1223. nsResState rs;
  1224. #endif
  1225. nsHostResolver *resolver = (nsHostResolver *)arg;
  1226. nsHostRecord *rec = nullptr;
  1227. AddrInfo *ai = nullptr;
  1228. while (rec || resolver->GetHostToLookup(&rec)) {
  1229. LOG(("DNS lookup thread - Calling getaddrinfo for host [%s%s%s].\n",
  1230. LOG_HOST(rec->host, rec->netInterface)));
  1231. #if TTL_AVAILABLE
  1232. bool getTtl = rec->mGetTtl;
  1233. #else
  1234. bool getTtl = false;
  1235. #endif
  1236. nsresult status = GetAddrInfo(rec->host, rec->af, rec->flags, rec->netInterface,
  1237. &ai, getTtl);
  1238. #if defined(RES_RETRY_ON_FAILURE)
  1239. if (NS_FAILED(status) && rs.Reset()) {
  1240. status = GetAddrInfo(rec->host, rec->af, rec->flags, rec->netInterface, &ai,
  1241. getTtl);
  1242. }
  1243. #endif
  1244. // OnLookupComplete may release "rec", long before we lose it.
  1245. LOG(("DNS lookup thread - lookup completed for host [%s%s%s]: %s.\n",
  1246. LOG_HOST(rec->host, rec->netInterface),
  1247. ai ? "success" : "failure: unknown host"));
  1248. if (LOOKUP_RESOLVEAGAIN == resolver->OnLookupComplete(rec, status, ai)) {
  1249. // leave 'rec' assigned and loop to make a renewed host resolve
  1250. LOG(("DNS lookup thread - Re-resolving host [%s%s%s].\n",
  1251. LOG_HOST(rec->host, rec->netInterface)));
  1252. } else {
  1253. rec = nullptr;
  1254. }
  1255. }
  1256. resolver->mThreadCount--;
  1257. NS_RELEASE(resolver);
  1258. LOG(("DNS lookup thread - queue empty, thread finished.\n"));
  1259. }
  1260. nsresult
  1261. nsHostResolver::Create(uint32_t maxCacheEntries,
  1262. uint32_t defaultCacheEntryLifetime,
  1263. uint32_t defaultGracePeriod,
  1264. nsHostResolver **result)
  1265. {
  1266. auto *res = new nsHostResolver(maxCacheEntries, defaultCacheEntryLifetime,
  1267. defaultGracePeriod);
  1268. NS_ADDREF(res);
  1269. nsresult rv = res->Init();
  1270. if (NS_FAILED(rv))
  1271. NS_RELEASE(res);
  1272. *result = res;
  1273. return rv;
  1274. }
  1275. void
  1276. nsHostResolver::GetDNSCacheEntries(nsTArray<DNSCacheEntries> *args)
  1277. {
  1278. for (auto iter = mDB.Iter(); !iter.Done(); iter.Next()) {
  1279. // We don't pay attention to address literals, only resolved domains.
  1280. // Also require a host.
  1281. auto entry = static_cast<nsHostDBEnt*>(iter.Get());
  1282. nsHostRecord* rec = entry->rec;
  1283. MOZ_ASSERT(rec, "rec should never be null here!");
  1284. if (!rec || !rec->addr_info || !rec->host) {
  1285. continue;
  1286. }
  1287. DNSCacheEntries info;
  1288. info.hostname = rec->host;
  1289. info.family = rec->af;
  1290. info.netInterface = rec->netInterface;
  1291. info.expiration =
  1292. (int64_t)(rec->mValidEnd - TimeStamp::NowLoRes()).ToSeconds();
  1293. if (info.expiration <= 0) {
  1294. // We only need valid DNS cache entries
  1295. continue;
  1296. }
  1297. {
  1298. MutexAutoLock lock(rec->addr_info_lock);
  1299. NetAddr *addr = nullptr;
  1300. NetAddrElement *addrElement = rec->addr_info->mAddresses.getFirst();
  1301. if (addrElement) {
  1302. addr = &addrElement->mAddress;
  1303. }
  1304. while (addr) {
  1305. char buf[kIPv6CStrBufSize];
  1306. if (NetAddrToString(addr, buf, sizeof(buf))) {
  1307. info.hostaddr.AppendElement(buf);
  1308. }
  1309. addr = nullptr;
  1310. addrElement = addrElement->getNext();
  1311. if (addrElement) {
  1312. addr = &addrElement->mAddress;
  1313. }
  1314. }
  1315. }
  1316. args->AppendElement(info);
  1317. }
  1318. }