Example #1
0
 vector<TSrvRecord> GetRecords(const string& host) const {
     ares_channel channel;
     int status;
     status = ares_init(&channel);
     if(status != ARES_SUCCESS) {
         throw UException(std::string("Failed to init ares channel: ") + ares_strerror(status));
     }
     TCallbackInfo info;
     ares_query(channel, host.c_str(), ns_c_in, ns_t_srv, callback, &info);
     wait_ares(channel);
     ares_destroy(channel);
     if (info.Status != ARES_SUCCESS) {
         throw UException(std::string("Failed to make ares request: ") + ares_strerror(info.Status));
     }
     struct ares_srv_reply* reply;
     status = ares_parse_srv_reply((const unsigned char*)info.Data.data(), info.Data.length(), &reply);
     if (info.Status != ARES_SUCCESS) {
         throw UException(std::string("Failed to parse response: ") + ares_strerror(status));
     }
     vector<TSrvRecord> records;
     struct ares_srv_reply* next = reply;
     while (next != NULL) {
         TSrvRecord record;
         record.Host = next->host;
         record.Port = next->port;
         record.Priority = next->priority;
         record.Weight = next->weight;
         records.push_back(record);
         next = next->next;
     }
     ares_free_data(reply);
     return records;
 }
Example #2
0
/* release memory */
void uv_ares_destroy(uv_loop_t* loop, ares_channel channel) {
  /* only allow destroy if did init */
  if (loop->ares_chan != NULL) {
    ares_destroy(channel);
    loop->ares_chan = NULL;
  }
}
Example #3
0
static void free_chan(ph_dns_channel_t *chan)
{
  ares_destroy(chan->chan);
  ph_ht_destroy(&chan->sock_map);
  pthread_mutex_destroy(&chan->chanlock);
  ph_mem_free(mt.chan, chan);
}
Example #4
0
/* Finds the SRV records for the given host. It returns the target IP
 * address and fills the port and transport if a suitable SRV record
 * exists. Otherwise it returns 0. The function follows 3263: first
 * TLS, then TCP and finally UDP. */
unsigned long getsrvadr(char *host, int *port, unsigned int *transport) {
	unsigned long adr = 0;

#ifdef HAVE_SRV
	int srvport = 5060;

#ifdef HAVE_CARES_H
	int status;
	int optmask = ARES_OPT_FLAGS;
	struct ares_options options;

	options.flags = ARES_FLAG_NOCHECKRESP;
	options.servers = NULL;
	options.nservers = 0;

	status = ares_init_options(&channel, &options, optmask);
	if (status != ARES_SUCCESS) {
		printf("error: failed to initialize ares\n");
		exit_code(2);
	}
#endif

#ifdef WITH_TLS_TRANSP
	adr = getsrvaddress(host, &srvport, SRV_SIP_TLS);
	if (adr != 0) {
		*transport = SIP_TLS_TRANSPORT;
		if (verbose > 1)
			printf("using SRV record: %s.%s:%i\n", SRV_SIP_TLS, host, srvport);
		printf("TLS transport not yet supported\n");
		exit_code(2);
	}
	else {
#endif
		adr = getsrvaddress(host, &srvport, SRV_SIP_TCP);
		if (adr != 0) {
			*transport = SIP_TCP_TRANSPORT;
			if (verbose > 1)
				printf("using SRV record: %s.%s:%i\n", SRV_SIP_TCP, host, srvport);
		}
		else {
			adr = getsrvaddress(host, &srvport, SRV_SIP_UDP);
			if (adr != 0) {
				*transport = SIP_UDP_TRANSPORT;
				if (verbose > 1)
					printf("using SRV record: %s.%s:%i\n", SRV_SIP_UDP, host, srvport);
			}
		}
#ifdef WITH_TLS_TRANSP
	}
#endif

#ifdef HAVE_CARES_H
	ares_destroy(channel);
#endif

	*port = srvport;
#endif // HAVE_SRV
	return adr;
}
Example #5
0
/* TODO share this with windows? */
void uv_ares_destroy(uv_loop_t* loop, ares_channel channel) {
  /* only allow destroy if did init */
  if (loop->channel) {
    uv__ares_timer_stop(loop);
    ares_destroy(channel);
    loop->channel = NULL;
  }
}
Example #6
0
/* TODO share this with windows? */
void uv_ares_destroy(ares_channel channel) {
  /* only allow destroy if did init */
  if (ares_data.channel != NULL) {
    ev_timer_stop(EV_DEFAULT_UC_ &ares_data.timer);
    ares_destroy(channel);
    ares_data.channel = NULL;
  }
}
Example #7
0
void
resolv_shutdown(struct ev_loop *loop)
{
    ares_cancel(default_ctx.channel);
    ares_destroy(default_ctx.channel);

    ares_library_cleanup();
}
static PyObject *
Channel_func_destroy(Channel *self)
{
    CHECK_CHANNEL(self);
    ares_destroy(self->channel);
    self->channel = NULL;
    Py_RETURN_NONE;
}
Example #9
0
int main(void) {
  ares_channel channelptr;

  ares_init(&channelptr);
  ares_destroy(channelptr);

  return 0;
}
Example #10
0
struct hostent *nssrs_resolver_by_servers(char *name, char *nameserver) {
    ares_channel channel = NULL;
    int status, optmask = 0;
    struct ares_options options;
    struct hostent *results;

    status = ares_library_init(ARES_LIB_INIT_ALL);
    if (status != ARES_SUCCESS) {
        debug("ares_library_init: %s\n", ares_strerror(status));
        return NULL;
    }

    optmask = ARES_OPT_SERVERS | ARES_OPT_UDP_PORT;
    options.servers  = NULL;
    options.nservers = 0;
    options.flags    = ARES_FLAG_NOCHECKRESP;

    status = ares_init_options(&channel, &options, optmask);
    if(status != ARES_SUCCESS) {
        debug("ares_init_options: %s\n", ares_strerror(status));
        return NULL;
    }

    status = ares_set_servers_csv(channel, nameserver);
    if (status != ARES_SUCCESS) {
      debug("ares_set_servers_csv: %s\n", ares_strerror(status));
      ares_destroy(channel);
      ares_library_cleanup();
      return NULL;
    }

    // Wait resolver
    results = malloc(sizeof(struct hostent));
    ares_gethostbyname(channel, name, AF_INET, &callback, results);
    wait_ares(channel);
    ares_destroy(channel);
    ares_library_cleanup();

    if (results->h_name != NULL) {
        return results;
    }

    free(results);
    return NULL;
}
Example #11
0
Resolver::~Resolver() 
{
    TORNADO_LOG_DEBUG_STR("---------------------------~Resolver");
    if(channel_)
    {
        ares_destroy(channel_);
        channel_ = nullptr;
    }
    cb_ = nullptr;
}
Example #12
0
/* the cleanup routine */
int
cleanup_dnsblc(void *state)
{
	ares_channel *channel;

	channel = (ares_channel *)state;
	ares_destroy(*channel);
	Free(channel);
	return 0;
}
static void
Channel_tp_dealloc(Channel *self)
{
    if (self->channel) {
        ares_destroy(self->channel);
        self->channel = NULL;
    }
    if (self->lib_initialized) {
        ares_library_cleanup();
    }
    Channel_tp_clear(self);
    Py_TYPE(self)->tp_free((PyObject *)self);
}
	void got_error() {
		if( curl )
			curl_easy_cleanup(curl);
		curl = 0;
		if( ares )
			ares_destroy( ares );
		ares = 0;
		if( headers ) {
			curl_slist_free_all(headers);
		}
		headers = 0;
		canceling = false;
		relocating = false;
		state = kError;
	}
Example #15
0
void OnEventDNSTask(int fd, short event, void *arg) {
    struct DNSTask *dnstask = (struct DNSTask *) arg;
    debug("event:%s, LobjId:%d, Hostname %s", getActionText(event), dnstask->task->LObjId, dnstask->task->Record.HostName);
    if (event & EV_READ) {
        ares_process_fd(dnstask->channel, fd, ARES_SOCKET_BAD);
    } else if (event & EV_TIMEOUT) {
        dnstask->task->code = STATE_TIMEOUT;
        dnstask->task->callback(dnstask->task);
    }

    if (!dnstask->isNeed) {
        ares_destroy(dnstask->channel);
        event_del(&dnstask->ev);
    }
}
Example #16
0
int
ecore_con_info_shutdown(void)
{
   info_init--;
   if (info_init == 0)
     {
        /* Cancel all ongoing request */
         ares_cancel(info_channel);
         ares_destroy(info_channel);

         /* Shutdown ares */
         ares_library_cleanup();
     }

   return info_init;
}
Example #17
0
void dns_finish_queries(listhead_t *activelist)
{
	listitem_t *walk;

	for (walk = activelist->head; (walk); walk = walk->next) {
		myconn_t *rec = (myconn_t *)walk->data;
		if (rec->talkprotocol != TALK_PROTO_DNSQUERY) continue;
		if (rec->dnsstatus != DNS_QUERY_COMPLETED) continue;

		dbgprintf("DNS query %s cleanup\n", rec->testspec);
		ares_destroy(*((ares_channel *)rec->dnschannel));
		xfree(rec->dnschannel);
		rec->dnsstatus = DNS_FINISHED;
	}

	/* Nothing to do for the lookup channel */
}
Example #18
0
	DNSHandler::DNSHandler (PanicType panic) : stop(false), panic(std::move(panic)) {
	
		//	Setup the completion callback
		complete=[this] (Query * q, bool) mutable noexcept {
		
			lock.Execute([&] () mutable {	queries.erase(q);	});
		
		};
	
		//	Check panic callback, if it's empty,
		//	default it to std::abort
		if (!panic) panic=[] (std::exception_ptr) {	std::abort();	};
	
		//	Initialize libcares
		auto result=ares_library_init(ARES_LIB_INIT_ALL);
		if (result!=0) raise(result);
		
		try {
		
			//	Prepare an asynchronous resolver
			//	channel
			if ((result=ares_init(&channel))!=0) raise(result);
			
			try {
			
				//	Create worker thread
				thread=Thread([this] () mutable {	worker_func();	});
			
			} catch (...) {
			
				ares_destroy(channel);
				
				throw;
			
			}
		
		} catch (...) {
		
			ares_library_cleanup();
			
			throw;
		
		}
	
	}
	void start_resolve() {
		if( ares ) {
			ares_destroy(ares);
			ares = 0;
		}
		state = kResolving;
		std::string actual_url = redirect_url.size() ? redirect_url:url;
		std::string host = extract_host(actual_url);
		std::string res = dns_cache->get_ent(host);
		if( !res.size() ) {
			ares_init(&ares);
			ares_gethostbyname(ares,host.c_str(),AF_INET,Request::GotResolveStatic,this);
		} else {
			char buf[1024];
			sprintf(buf,"%d.%d.%d.%d",res[0],res[1],res[2],res[3]);
			direct_ip = buf;
			state = kStartDownload;
		}
	}
	void cleanup() {
		if( curl ) {
			curl_easy_cleanup(curl);
		}
		curl = 0;
		if( ares )
			ares_destroy( ares );
		ares = 0;
		if( headers ) {
			curl_slist_free_all(headers);
		}
		headers = 0;
		errmsg = "";
		content = "";
		url = "";
		state = kNone;
		canceling = false;
		relocating = false;
	}
Example #21
0
	DNSHandler::~DNSHandler () noexcept {
	
		//	Shutdown the worker
		
		try {
		
			issue_command(true);
		
		} catch (...) {
		
			try {
			
				panic(std::current_exception());
			
			} catch (...) {	}
			
			//	If the panic function returns,
			//	we can't do anything constructive
			//	at this point, so kill the whole
			//	process.
			std::abort();
		
		}
		
		lock.Execute([&] () mutable {
		
			stop=true;
			
			wait.WakeAll();
		
		});
		
		thread.Join();
	
		//	Cleanup the asynchronous resolver channel
		ares_destroy(channel);
		
		//	Cleanup libcares
		ares_library_cleanup();
	
	}
	void got_done() {
		if( curl )
			curl_easy_cleanup(curl);
		curl = 0;
		if( ares )
			ares_destroy( ares );
		ares = 0;
		if( headers ) {
			curl_slist_free_all(headers);
		}
		headers = 0;
		if( relocating ) {
			relocating = false;
			state = kStarting;
			start(curlm,curlsh,dns_cache);
		} else {
			state = kOK;
			canceling = false;
			relocating = false;
		}
	}
Example #23
0
// Bad synchronous gethostbyname demo
uint32_t tm__sync_gethostbyname (const char *domain)
{
    ares_channel channel;
    int status;
    struct ares_options options;
    int optmask = 0;

    ipaddr[0] = ipaddr[1] = ipaddr[2] = ipaddr[3] = 0;

    struct in_addr ns1;

    inet_aton("8.8.8.8",&ns1);
 
    status = ares_library_init(ARES_LIB_INIT_ALL);
    if (status != ARES_SUCCESS){
        printf("ares_library_init: %s\n", ares_strerror(status));
        return 1;
    }
    options.servers = &ns1;
    options.nservers = 1;
    optmask |= ARES_OPT_SERVERS;
    options.sock_state_cb = state_cb;
    // options.sock_state_cb_data;
    optmask |= ARES_OPT_SOCK_STATE_CB;
 
    status = ares_init_options(&channel, &options, optmask);
    if(status != ARES_SUCCESS) {
        printf("ares_init_options: %s\n", ares_strerror(status));
        return 1;
    }
 
    ares_gethostbyname(channel, domain, AF_INET, callback, NULL);
    wait_ares(channel);
    ares_destroy(channel);
    ares_library_cleanup();
    // printf("fin\n");
    // printf("result => %d.%d.%d.%d\n", ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3]);

    return (ipaddr[0] << 24) | (ipaddr[1] << 16) | (ipaddr[2] << 8) | ipaddr[3];
}
Example #24
0
void APE_destroy(ape_global *ape)
{
    //  destroying dns
    struct _ares_sockets *as;
    size_t i;

    ares_cancel(ape->dns.channel);
    as = ape->dns.sockets.list;

    for (i = 0; i < ape->dns.sockets.size; i++) {
        events_del(as->s.fd, ape);
        as++;
    }

    free(ape->dns.sockets.list);
    ape->dns.sockets.size = 0;
    ape->dns.sockets.used = 0;
    ares_destroy(ape->dns.channel);
    ares_library_cleanup();

    //  destroying events
    events_destroy(&ape->events);
    // destroying timers
    APE_timers_destroy_all(ape);

    if (ape->ssl_global_ctx) {
        ape_ssl_shutdown(ape->ssl_global_ctx);
        ape_ssl_destroy(ape->ssl_global_ctx);
    }
    ape_ssl_library_destroy();

    close(ape->urandom_fd);
    if (ape->logger.cleanup) {
        ape->logger.cleanup(ape->logger.ctx, ape->logger.cb_args);
    }
    //  destroying rest
    free(ape);

    pthread_setspecific(g_APEThreadContextKey, NULL);
}
Example #25
0
eNextState ShutDownCLient(AsyncIO *IO)
{
	CitContext *Ctx =IO->CitContext;

	SetEVState(IO, eExit);
	become_session(Ctx);

	EVM_syslog(LOG_DEBUG, "EVENT Terminating \n");

	StopClientWatchers(IO, 1);

	if (IO->DNS.Channel != NULL) {
		ares_destroy(IO->DNS.Channel);
		EV_DNS_LOG_STOP(DNS.recv_event);
		EV_DNS_LOG_STOP(DNS.send_event);
		ev_io_stop(event_base, &IO->DNS.recv_event);
		ev_io_stop(event_base, &IO->DNS.send_event);
		IO->DNS.Channel = NULL;
	}
	assert(IO->Terminate);
	return IO->Terminate(IO);
}
Example #26
0
void tt_dns_destroy_ntv(IN ares_channel ch)
{
    __dskt_t *dskt = (__dskt_t *)ch->sock_create_cb_data;
    int n = __DSKT_NUM(ch);

    // ares_destroy() need access dskt array as it would close
    // all sockets. so ares_destroy() must be called before
    // __dskt_destroy()
    ares_destroy(ch);

    if (dskt != NULL) {
        int i;
        for (i = 0; i < n; ++i) {
            // no matter whether the dskt is in reading or writing
            // as this function is generally called when io poller
            // thread is terminated, __do_read/write/connect won't
            // be called
            __dskt_destroy(&dskt[i]);
        }

        tt_free(dskt);
    }
}
	void step() {
		if( state == kResolving ) {
			if( ares ) {
				if( canceling ) {
					ares_cancel(ares);
				}
				int nfds, count;
				fd_set readers, writers;
				struct timeval tv, maxtv, *tvp;
				FD_ZERO(&readers);
				FD_ZERO(&writers);
				nfds = ares_fds(ares, &readers, &writers);
				maxtv.tv_sec = 0;
				maxtv.tv_usec = 1000;
				if (nfds == 0) {
					ares_process(ares, NULL, NULL);
				} else {
					tvp = ares_timeout(ares, &maxtv, &tv);
					count = select(nfds, &readers, &writers, NULL, tvp);
					ares_process(ares, &readers, &writers);
				}
			}
		}
		if( state == kStartDownload ) {
			if( ares )
				ares_destroy( ares );
			ares = 0;
			start_curl();
		}
		if( state == kFinishingOK ) {
			got_done();
		}
		if( state == kFinishingError ) {
			got_error();
		}
		// Nothing to do with other states
	}
/*
 * Curl_resolver_cleanup()
 *
 * Called from curl_easy_cleanup() -> Curl_close() to cleanup resolver
 * URL-state specific environment ('resolver' member of the UrlState
 * structure).  Destroys the ares channel.
 */
void Curl_resolver_cleanup(void *resolver)
{
  ares_destroy((ares_channel)resolver);
}
Example #29
0
LLAres::~LLAres()
{
	ares_destroy(chan_);
	ares_library_cleanup();
}
Example #30
0
int main(int argc, char **argv)
{
  ares_channel channel;
  int c, i, optmask = ARES_OPT_FLAGS, dnsclass = C_IN, type = T_A;
  int status, nfds, count;
  struct ares_options options;
  struct hostent *hostent;
  fd_set read_fds, write_fds;
  struct timeval *tvp, tv;
  struct ares_addr_node *srvr, *servers = NULL;

#ifdef USE_WINSOCK
  WORD wVersionRequested = MAKEWORD(USE_WINSOCK,USE_WINSOCK);
  WSADATA wsaData;
  WSAStartup(wVersionRequested, &wsaData);
#endif

  status = ares_library_init(ARES_LIB_INIT_ALL);
  if (status != ARES_SUCCESS)
    {
      fprintf(stderr, "ares_library_init: %s\n", ares_strerror(status));
      return 1;
    }

  options.flags = ARES_FLAG_NOCHECKRESP;
  options.servers = NULL;
  options.nservers = 0;
  while ((c = ares_getopt(argc, argv, "df:s:c:t:T:U:")) != -1)
    {
      switch (c)
        {
        case 'd':
#ifdef WATT32
          dbug_init();
#endif
          break;

        case 'f':
          /* Add a flag. */
          for (i = 0; i < nflags; i++)
            {
              if (strcmp(flags[i].name, optarg) == 0)
                break;
            }
          if (i < nflags)
            options.flags |= flags[i].value;
          else
            usage();
          break;

        case 's':
          /* User-specified name servers override default ones. */
          srvr = malloc(sizeof(struct ares_addr_node));
          if (!srvr)
            {
              fprintf(stderr, "Out of memory!\n");
              destroy_addr_list(servers);
              return 1;
            }
          append_addr_list(&servers, srvr);
          if (ares_inet_pton(AF_INET, optarg, &srvr->addr.addr4) > 0)
            srvr->family = AF_INET;
          else if (ares_inet_pton(AF_INET6, optarg, &srvr->addr.addr6) > 0)
            srvr->family = AF_INET6;
          else
            {
              hostent = gethostbyname(optarg);
              if (!hostent)
                {
                  fprintf(stderr, "adig: server %s not found.\n", optarg);
                  destroy_addr_list(servers);
                  return 1;
                }
              switch (hostent->h_addrtype)
                {
                  case AF_INET:
                    srvr->family = AF_INET;
                    memcpy(&srvr->addr.addr4, hostent->h_addr,
                           sizeof(srvr->addr.addr4));
                    break;
                  case AF_INET6:
                    srvr->family = AF_INET6;
                    memcpy(&srvr->addr.addr6, hostent->h_addr,
                           sizeof(srvr->addr.addr6));
                    break;
                  default:
                    fprintf(stderr,
                      "adig: server %s unsupported address family.\n", optarg);
                    destroy_addr_list(servers);
                    return 1;
                }
            }
          /* Notice that calling ares_init_options() without servers in the
           * options struct and with ARES_OPT_SERVERS set simultaneously in
           * the options mask, results in an initialization with no servers.
           * When alternative name servers have been specified these are set
           * later calling ares_set_servers() overriding any existing server
           * configuration. To prevent initial configuration with default
           * servers that will be discarded later, ARES_OPT_SERVERS is set.
           * If this flag is not set here the result shall be the same but
           * ares_init_options() will do needless work. */
          optmask |= ARES_OPT_SERVERS;
          break;

        case 'c':
          /* Set the query class. */
          for (i = 0; i < nclasses; i++)
            {
              if (strcasecmp(classes[i].name, optarg) == 0)
                break;
            }
          if (i < nclasses)
            dnsclass = classes[i].value;
          else
            usage();
          break;

        case 't':
          /* Set the query type. */
          for (i = 0; i < ntypes; i++)
            {
              if (strcasecmp(types[i].name, optarg) == 0)
                break;
            }
          if (i < ntypes)
            type = types[i].value;
          else
            usage();
          break;

        case 'T':
          /* Set the TCP port number. */
          if (!ISDIGIT(*optarg))
            usage();
          options.tcp_port = (unsigned short)strtol(optarg, NULL, 0);
          optmask |= ARES_OPT_TCP_PORT;
          break;

        case 'U':
          /* Set the UDP port number. */
          if (!ISDIGIT(*optarg))
            usage();
          options.udp_port = (unsigned short)strtol(optarg, NULL, 0);
          optmask |= ARES_OPT_UDP_PORT;
          break;
        }
    }
  argc -= optind;
  argv += optind;
  if (argc == 0)
    usage();

  status = ares_init_options(&channel, &options, optmask);

  if (status != ARES_SUCCESS)
    {
      fprintf(stderr, "ares_init_options: %s\n",
              ares_strerror(status));
      return 1;
    }

  if(servers)
    {
      status = ares_set_servers(channel, servers);
      destroy_addr_list(servers);
      if (status != ARES_SUCCESS)
        {
          fprintf(stderr, "ares_init_options: %s\n",
                  ares_strerror(status));
          return 1;
        }
    }

  /* Initiate the queries, one per command-line argument.  If there is
   * only one query to do, supply NULL as the callback argument;
   * otherwise, supply the query name as an argument so we can
   * distinguish responses for the user when printing them out.
   */
  if (argc == 1)
    ares_query(channel, *argv, dnsclass, type, callback, (char *) NULL);
  else
    {
      for (; *argv; argv++)
        ares_query(channel, *argv, dnsclass, type, callback, *argv);
    }

  /* Wait for all queries to complete. */
  for (;;)
    {
      FD_ZERO(&read_fds);
      FD_ZERO(&write_fds);
      nfds = ares_fds(channel, &read_fds, &write_fds);
      if (nfds == 0)
        break;
      tvp = ares_timeout(channel, NULL, &tv);
      count = select(nfds, &read_fds, &write_fds, NULL, tvp);
      if (count < 0 && SOCKERRNO != EINVAL)
        {
          perror("select");
          return 1;
        }
      ares_process(channel, &read_fds, &write_fds);
    }

  ares_destroy(channel);

  ares_library_cleanup();

#ifdef USE_WINSOCK
  WSACleanup();
#endif

  return 0;
}