68 lines
2.0 KiB
C
Raw Normal View History

2018-12-14 16:28:11 -08:00
/*
* IXDNSLookup.h
* Author: Benjamin Sergeant
* Copyright (c) 2018 Machine Zone, Inc. All rights reserved.
*
* Resolve a hostname+port to a struct addrinfo obtained with getaddrinfo
2018-12-14 16:28:11 -08:00
* Does this in a background thread so that it can be cancelled, since
* getaddrinfo is a blocking call, and we don't want to block the main thread on Mobile.
*/
#pragma once
#include "IXCancellationRequest.h"
#include <atomic>
#include <cstdint>
2019-08-13 10:59:18 -07:00
#include <memory>
2019-06-26 19:12:48 -07:00
#include <mutex>
2018-12-14 17:49:42 -08:00
#include <set>
2019-05-30 08:46:50 -07:00
#include <string>
2018-12-14 16:28:11 -08:00
struct addrinfo;
namespace ix
2018-12-14 16:28:11 -08:00
{
class DNSLookup : public std::enable_shared_from_this<DNSLookup>
2019-05-30 08:46:50 -07:00
{
2018-12-14 16:28:11 -08:00
public:
using AddrInfoPtr = std::shared_ptr<addrinfo>;
2019-05-30 08:46:50 -07:00
DNSLookup(const std::string& hostname, int port, int64_t wait = DNSLookup::kDefaultWait);
~DNSLookup() = default;
2018-12-14 16:28:11 -08:00
AddrInfoPtr resolve(std::string& errMsg,
2018-12-14 16:28:11 -08:00
const CancellationRequest& isCancellationRequested,
bool cancellable = true);
2018-12-14 16:28:11 -08:00
private:
AddrInfoPtr resolveCancellable(std::string& errMsg,
const CancellationRequest& isCancellationRequested);
AddrInfoPtr resolveUnCancellable(std::string& errMsg,
const CancellationRequest& isCancellationRequested);
2018-12-14 16:28:11 -08:00
AddrInfoPtr getAddrInfo(const std::string& hostname,
2018-12-14 16:28:11 -08:00
int port,
std::string& errMsg);
2019-06-26 16:25:07 -07:00
void run(std::weak_ptr<DNSLookup> self, std::string hostname, int port); // thread runner
void setErrMsg(const std::string& errMsg);
const std::string& getErrMsg();
void setRes(AddrInfoPtr addr);
AddrInfoPtr getRes();
2018-12-14 16:28:11 -08:00
std::string _hostname;
int _port;
2018-12-23 14:14:38 -08:00
int64_t _wait;
const static int64_t kDefaultWait;
AddrInfoPtr _res;
std::mutex _resMutex;
std::string _errMsg;
std::mutex _errMsgMutex;
2018-12-14 16:28:11 -08:00
std::atomic<bool> _done;
};
2019-05-30 08:46:50 -07:00
} // namespace ix