You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.0 KiB

4 months ago
  1. /*
  2. * IXDNSLookup.h
  3. * Author: Benjamin Sergeant
  4. * Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
  5. *
  6. * Resolve a hostname+port to a struct addrinfo obtained with getaddrinfo
  7. * Does this in a background thread so that it can be cancelled, since
  8. * getaddrinfo is a blocking call, and we don't want to block the main thread on Mobile.
  9. */
  10. #pragma once
  11. #include "IXCancellationRequest.h"
  12. #include <atomic>
  13. #include <memory>
  14. #include <mutex>
  15. #include <set>
  16. #include <string>
  17. struct addrinfo;
  18. namespace ix
  19. {
  20. class DNSLookup : public std::enable_shared_from_this<DNSLookup>
  21. {
  22. public:
  23. DNSLookup(const std::string& hostname, int port, int64_t wait = DNSLookup::kDefaultWait);
  24. ~DNSLookup() = default;
  25. struct addrinfo* resolve(std::string& errMsg,
  26. const CancellationRequest& isCancellationRequested,
  27. bool cancellable = true);
  28. void release(struct addrinfo* addr);
  29. private:
  30. struct addrinfo* resolveCancellable(std::string& errMsg,
  31. const CancellationRequest& isCancellationRequested);
  32. struct addrinfo* resolveUnCancellable(std::string& errMsg,
  33. const CancellationRequest& isCancellationRequested);
  34. static struct addrinfo* getAddrInfo(const std::string& hostname,
  35. int port,
  36. std::string& errMsg);
  37. void run(std::weak_ptr<DNSLookup> self, std::string hostname, int port); // thread runner
  38. void setErrMsg(const std::string& errMsg);
  39. const std::string& getErrMsg();
  40. void setRes(struct addrinfo* addr);
  41. struct addrinfo* getRes();
  42. std::string _hostname;
  43. int _port;
  44. int64_t _wait;
  45. const static int64_t kDefaultWait;
  46. struct addrinfo* _res;
  47. std::mutex _resMutex;
  48. std::string _errMsg;
  49. std::mutex _errMsgMutex;
  50. std::atomic<bool> _done;
  51. };
  52. } // namespace ix