Esempio n. 1
0
 ConnectionError Client::recv( int timeout )
 {
   if( m_connection && m_connection->state() == StateConnected )
     return ClientBase::recv( timeout );
   else
   {
     if( !m_currentRef )
       return ConnNoError;
     
     struct timeval tv;
     
     fd_set fds;
     FD_ZERO( &fds );
     // the following causes a C4127 warning in VC++ Express 2008 and possibly other versions.
     // however, the reason for the warning can't be fixed in gloox.
     FD_SET( DNSServiceRefSockFD( m_currentRef ), &fds );
     
     tv.tv_sec = timeout / 1000000;
     tv.tv_usec = timeout % 1000000;
     
     if( select( FD_SETSIZE, &fds, 0, 0, timeout == -1 ? 0 : &tv ) > 0 )
     {
       if( FD_ISSET( DNSServiceRefSockFD( m_currentRef ), &fds ) != 0 )
         DNSServiceProcessResult( m_currentRef );
     }
     
     return ConnNoError;
   }
 }
OSStatus
CConfigPropertySheet::SetupBrowsing()
{
	OSStatus err;

	// Start browsing for browse domains

	err = DNSServiceEnumerateDomains( &m_browseDomainsRef, kDNSServiceFlagsBrowseDomains, 0, BrowseDomainsReply, this );
	require_noerr( err, exit );

	err = WSAAsyncSelect( DNSServiceRefSockFD( m_browseDomainsRef ), m_hWnd, WM_DATAREADY, FD_READ|FD_CLOSE );
	require_noerr( err, exit );

	// Start browsing for registration domains

	err = DNSServiceEnumerateDomains( &m_regDomainsRef, kDNSServiceFlagsRegistrationDomains, 0, RegDomainsReply, this );
	require_noerr( err, exit );

	err = WSAAsyncSelect( DNSServiceRefSockFD( m_regDomainsRef ), m_hWnd, WM_DATAREADY, FD_READ|FD_CLOSE );
	require_noerr( err, exit );

exit:

	if ( err )
	{
		TearDownBrowsing();
	}

	return err;
}
OSStatus
CConfigPropertySheet::TearDownBrowsing()
{
	OSStatus err = kNoErr;

	if ( m_browseDomainsRef )
	{
		err = WSAAsyncSelect( DNSServiceRefSockFD( m_browseDomainsRef ), m_hWnd, 0, 0 );
		check_noerr( err );

		DNSServiceRefDeallocate( m_browseDomainsRef );
	
		m_browseDomainsRef = NULL;
	}

	if ( m_regDomainsRef )
	{
		err = WSAAsyncSelect( DNSServiceRefSockFD( m_regDomainsRef ), m_hWnd, 0, 0 );
		check_noerr( err );

		DNSServiceRefDeallocate( m_regDomainsRef );
	
		m_regDomainsRef = NULL;
	}

	return err;
}
Esempio n. 4
0
/* IBFDNSSDService enumerate (in long interfaceIndex, in PRBool domainType, in IBFDNSSDEnumerateListener listener); */
NS_IMETHODIMP
CBFDNSSDService::Enumerate(PRInt32 interfaceIndex, PRBool domainType, IBFDNSSDEnumerateListener *listener, IBFDNSSDService **_retval)
{
	CBFDNSSDService	*	service	= NULL;
	DNSServiceErrorType dnsErr	= 0;
	nsresult			err		= 0;

	*_retval = NULL;
	
	try
	{
		service = new CBFDNSSDService( listener );
	}
	catch ( ... )
	{
		service = NULL;
	}
	
	if ( service == NULL )
	{
		err = NS_ERROR_FAILURE;
		goto exit;
	}
	service->m_enuDomainType = domainType;
	dnsErr = DNSServiceEnumerateDomains( &service->m_sdRef, domainType ? kDNSServiceFlagsBrowseDomains : kDNSServiceFlagsRegistrationDomains, interfaceIndex, ( DNSServiceDomainEnumReply ) EnumerateReply, service );
	if ( dnsErr != kDNSServiceErr_NoError )
	{
		err = NS_ERROR_FAILURE;
		goto exit;
	}
	if ( ( service->m_fileDesc = PR_ImportTCPSocket( DNSServiceRefSockFD( service->m_sdRef ) ) ) == NULL )
	{
		err = NS_ERROR_FAILURE;
		goto exit;
	}
	if ( ( service->m_threadPool = PR_CreateThreadPool( 1, 1, 8192 ) ) == NULL )
	{
		err = NS_ERROR_FAILURE;
		goto exit;
	}
	err = service->SetupNotifications();
	if ( err != NS_OK)
	{
	    goto exit;
	}
	listener->AddRef();
	service->AddRef();
	*_retval = service;
	err = NS_OK;

exit:

	if ( err && service )
	{
		delete service;
		service = NULL;
	}
	
	return err;
}
  void register_service(DNSServiceRef service) {
    // Run until break.
    int dns_sd_fd = DNSServiceRefSockFD(service);
    fd_set readfds;
    struct timeval tv;
    int result;

    while (should_run()) {
      FD_ZERO(&readfds);
      FD_SET(dns_sd_fd, &readfds);
      tv.tv_sec = LONG_TIME;
      tv.tv_usec = 0;
                      // highest fd in set + 1
      result = select(dns_sd_fd+1, &readfds, (fd_set*)NULL, (fd_set*)NULL, &tv);
      if (result > 0) {
        DNSServiceErrorType err = kDNSServiceErr_NoError;
        // Execute callback
        if (FD_ISSET(dns_sd_fd, &readfds)) err = DNSServiceProcessResult(service);

        if (err) {
          // An error occured. Halt.
          fprintf(stderr, "DNSServiceProcessResult returned %d\n", err);
          quit();
        }
      }	else if (errno != EINTR) {
        // Error.
        fprintf(stderr, "ZeroConf error (%d %s)\n", errno, strerror(errno));
        if (errno != EINTR) quit();
      }
    }
  }
void BonjourServiceResolver::resolveBonjourRecord( const BonjourRecord& record )
{
    if( isResolving() )
    {
        qWarning("resolve in process, aborting");
        return;
    }
    const DNSServiceErrorType err = DNSServiceResolve( &d->dnssref, 0, 0, record.serviceName.toUtf8().constData(), record.registeredType.toUtf8().constData(),
                                                       record.replyDomain.toUtf8().constData(), Private::bonjourResolveReply, d );
    if( err != kDNSServiceErr_NoError )
    {
        error( err );
    } 
    else 
    {
        const int sockfd = DNSServiceRefSockFD( d->dnssref );
        if( sockfd == -1 )
        {
            error( kDNSServiceErr_Invalid );
        } 
        else 
        {
            Q_ASSERT( d->bonjourSocket == 0 );
            d->bonjourSocket = new QSocketNotifier( sockfd, QSocketNotifier::Read, this );
            connect( d->bonjourSocket, SIGNAL( activated( int ) ), this, SLOT( bonjourSocketReadyRead() ) );
        }
    }
}
Esempio n. 7
0
bool MLNetServiceHub::pollService(DNSServiceRef dnsServiceRef, double timeOutInSeconds, DNSServiceErrorType &err)
{
	assert(dnsServiceRef);

	err = kDNSServiceErr_NoError;
	
  fd_set readfds;
	FD_ZERO(&readfds);
	
  int dns_sd_fd = DNSServiceRefSockFD(dnsServiceRef);
  int nfds = dns_sd_fd+1;
	FD_SET(dns_sd_fd, &readfds);
	
  struct timeval tv;
  tv.tv_sec = long(floor(timeOutInSeconds));
  tv.tv_usec = long(1000000*(timeOutInSeconds - tv.tv_sec));
	
	int result = select(nfds,&readfds,NULL,NULL,&tv);
	if(result>0 && FD_ISSET(dns_sd_fd, &readfds))
	{
		err = DNSServiceProcessResult(dnsServiceRef);
		return true;
	}
	
	return false;
}
Esempio n. 8
0
void
register_service (int port)
{
    int dnsfd;
    GSource *source;

    if (DNSServiceRegister (&g_sdref, 0, 0, NULL, "_xmms2._tcp", NULL, NULL,
                            g_htons (port), 0, NULL, dns_callback, NULL)
            != kDNSServiceErr_NoError) {
        printf ("failed to register!\n");
        exit (1);
    }

    dnsfd = DNSServiceRefSockFD (g_sdref);
    if (dnsfd == -1) {
        printf ("no fd!?\n");
        exit (1);
    }

    pollfd = g_new0 (GPollFD, 1);
    pollfd->fd = dnsfd;
    pollfd->events = G_IO_IN | G_IO_HUP | G_IO_ERR;

    source = g_source_new (&dns_ipc_func, sizeof (GSource));

    g_source_add_poll (source, pollfd);
    g_source_attach (source, NULL);
}
Esempio n. 9
0
LONG
CSecondPage::OnServiceEvent(WPARAM inWParam, LPARAM inLParam)
{
	if (WSAGETSELECTERROR(inLParam) && !(HIWORD(inLParam)))
    {
		dlog( kDebugLevelError, "OnServiceEvent: window error\n" );
    }
    else
    {
		SOCKET sock = (SOCKET) inWParam;

		// iterate thru list
		ServiceRefList::iterator begin = m_serviceRefList.begin();
		ServiceRefList::iterator end   = m_serviceRefList.end();

		while (begin != end)
		{
			DNSServiceRef ref = *begin++;

			check(ref != NULL);

			if ((SOCKET) DNSServiceRefSockFD(ref) == sock)
			{
				DNSServiceProcessResult(ref);
				break;
			}
		}
	}

	return ( 0 );
}
Esempio n. 10
0
/*!
 * Attempts to resolve the service in order to determine the host and port necessary to establish a connection.
 *
 * If forceMulticast is set to true, QxtDiscoverableService will use a multicast request to resolve the service,
 * even if the host name appears to be a unicast address (that is, outside the local network).
 *
 * \sa resolved
 * \sa resolveError
 */
void QxtDiscoverableService::resolve(bool forceMulticast)
{
    if(state() != Unknown && state() != Found) {
        qWarning() << "QxtDiscoverableService: Cannot resolve service while not in Unknown or Found state";
        emit resolveError(0);
        return;
    }

    DNSServiceErrorType err;
    err = DNSServiceResolve(&(qxt_d().service),
                            (forceMulticast ? kDNSServiceFlagsForceMulticast : 0),
                            qxt_d().iface,
                            serviceName().toUtf8().constData(),
                            fullServiceType().constData(),
                            domain().toUtf8().constData(),
                            QxtDiscoverableServicePrivate::resolveServiceCallback,
                            &qxt_d());
    if(err != kDNSServiceErr_NoError) {
        qxt_d().state = Unknown;
        emit resolveError(err);
    } else {
        qxt_d().state = Resolving;
        qxt_d().notifier = new QSocketNotifier(DNSServiceRefSockFD(qxt_d().service), QSocketNotifier::Read, this);
        QObject::connect(qxt_d().notifier, SIGNAL(activated(int)), &qxt_d(), SLOT(socketData()));
    }
}
Esempio n. 11
0
void ProcessDNSMessages() {
	static boolean initialized;
	
	if ( !initialized ) {
		initialized = true;
		DNSServiceErrorType err = DNSServiceBrowse ( 
													&browseRef, 
													0,					/* flags */
													0,					/* interface */
													serviceName, 
													NULL,				/* domain */
													DNSServiceBrowseReplyCallback, 
													NULL				/* context */
													);  
		if ( err != kDNSServiceErr_NoError ) {
			printf( "DNSServiceBrowse error\n" );
			return;
		}		
	}
	
	// poll the socket for updates
	int	socket = DNSServiceRefSockFD( browseRef );
	if ( socket <= 0 ) {
		return;
	}
	fd_set	set;
	FD_ZERO( &set );
	FD_SET( socket, &set );
	
	struct timeval tv;
	memset( &tv, 0, sizeof( tv ) );
	if ( select( socket+1, &set, NULL, NULL, &tv ) > 0 ) {
		DNSServiceProcessResult( browseRef );
	}	
}
static gboolean
g_mdns_poll_add (GMDNS *mdns, GMDNSUserData *ud, DNSServiceRef client)
{
	ud->fd = g_new0 (GPollFD, 1);
	ud->fd->fd = DNSServiceRefSockFD (client);
	ud->client = client;
	ud->mdns = mdns;

	if (ud->fd->fd == -1) {
		g_free (ud->fd);
		g_free (ud);
		return FALSE;
	}

	ud->fd->events = G_IO_IN | G_IO_HUP | G_IO_ERR;

	ud->source = g_source_new (&g_mdns_poll_funcs, sizeof (GSource));
	g_source_set_callback (ud->source,
	                       (GSourceFunc) g_mdns_source_dispatch,
	                       ud, NULL);
	g_source_add_poll (ud->source, ud->fd);
	g_source_attach (ud->source, NULL);

	return TRUE;
}
Esempio n. 13
0
/*
 * DnsServiceRegistrar::add
 *
 * Registers a new service.
 *
 * Parameters:
 *	- type: service type
 *	- port: port number of the registered service
 *	- name: service name (optional)
 *
 * Return value: reference of the DNS service if registration was successful, NULL otherwise
 */
DNSServiceRef DnsServiceRegistrar::add(const QString& type, quint16 port, const QString& name)
{
    /* Deal with name default value */
    char *nameStr;
    if (name == "") {
        nameStr = NULL;
    } else {
        nameStr = name.toUtf8().data();
    }

    /* Create and register the new service ref. */
    DNSServiceRef ref;
     DNSServiceErrorType err = DNSServiceRegister(&ref, 0, 0, nameStr, type.toUtf8().data(), NULL,
                                                                 NULL, qToBigEndian(port), 0, NULL, registerCallback, this);
    if (err != kDNSServiceErr_NoError) {
        Model::logger().addEntry(Logger::Error, QString("Error while registering service (error code = %1)").arg(err));
        return NULL;
    }

    /* Create the QSocketNotifier */
    int sockFd = DNSServiceRefSockFD(ref);
    RefNotifier *pNotif = new RefNotifier(ref, sockFd, QSocketNotifier::Read, this);
    connect(pNotif, SIGNAL(activated(int)), this, SLOT(onNotifierActivated()));

    return ref;
}
Esempio n. 14
0
void AutoDiscoveryServerImpl::update()
{
    int dns_sd_fd  = client    ? DNSServiceRefSockFD(client   ) : -1;
    int nfds = dns_sd_fd + 1;
    fd_set readfds;
    struct timeval tv;
    int result;
    
//     (dns_sd_fd2 > dns_sd_fd) nfds = dns_sd_fd2 + 1;

    // 1. Set up the fd_set as usual here.
    // This example client has no file descriptors of its own,
    // but a real application would call FD_SET to add them to the set here
    FD_ZERO(&readfds);

    // 2. Add the fd for our client(s) to the fd_set
    if (client   ) FD_SET(dns_sd_fd , &readfds);
    //if (client_pa) FD_SET(dns_sd_fd2, &readfds);

    // 3. Set up the timeout.
    tv.tv_sec  = 0;
    tv.tv_usec = 0;

    result = select(nfds, &readfds, (fd_set*)NULL, (fd_set*)NULL, &tv);
    if (result > 0)
    {
        DNSServiceErrorType err = kDNSServiceErr_NoError;
        if      (client    && FD_ISSET(dns_sd_fd , &readfds)) err = DNSServiceProcessResult(client   );
//        else if (client_pa && FD_ISSET(dns_sd_fd2, &readfds)) err = DNSServiceProcessResult(client_pa);
//        if (err) { fprintf(stderr, "DNSServiceProcessResult returned %d\n", err); stopNow = 1; }
    }
}
Esempio n. 15
0
void CZeroconfMDNS::doStop()
{
  {
    CSingleLock lock(m_data_guard);
    CLog::Log(LOGDEBUG, "ZeroconfMDNS: Shutdown services");
    for(tServiceMap::iterator it = m_services.begin(); it != m_services.end(); ++it)
    {
      DNSServiceRefDeallocate(it->second.serviceRef);
      TXTRecordDeallocate(&it->second.txtRecordRef);
      CLog::Log(LOGDEBUG, "ZeroconfMDNS: Removed service %s", it->first.c_str());
    }
    m_services.clear();
  }
  {
    CSingleLock lock(m_data_guard);
#if defined(TARGET_WINDOWS_STORE)
    CLog::Log(LOGERROR, "ZeroconfMDNS: WSAAsyncSelect not yet supported for TARGET_WINDOWS_STORE");
#else
    WSAAsyncSelect( (SOCKET) DNSServiceRefSockFD( m_service ), g_hWnd, BONJOUR_EVENT, 0 );
#endif //TARGET_WINDOWS

    if (m_service)
      DNSServiceRefDeallocate(m_service);
    m_service = NULL;
  }
}
Esempio n. 16
0
/*!
 * Attempts to register the service on the local network.
 *
 * If noAutoRename is set to true, registration will fail if another service of the same service type
 * is already registered with the same service name. Otherwise, the service name will be updated with
 * a number to make it unique.
 *
 * \sa registered
 * \sa registrationError
 */
void QxtDiscoverableService::registerService(bool noAutoRename)
{
    if(state() != Unknown) {
        qWarning() << "QxtDiscoverableService: Cannot register service while not in Unknown state";
        emit registrationError(0);
        return;
    }

    QStringList subtypes = qxt_d().serviceSubTypes;
    subtypes.prepend(fullServiceType());

    DNSServiceErrorType err;
    err = DNSServiceRegister(&(qxt_d().service),
                             noAutoRename ? kDNSServiceFlagsNoAutoRename : 0,
                             qxt_d().iface,
                             serviceName().isEmpty() ? 0 : serviceName().toUtf8().constData(),
                             subtypes.join(",_").toUtf8().constData(),
                             domain().isEmpty() ? 0 : domain().toUtf8().constData(),
                             host().isEmpty() ? 0 : host().toUtf8().constData(),
                             qxt_d().port,
                             1, // must include null terminator
                             "",
                             QxtDiscoverableServicePrivate::registerServiceCallback,
                             &qxt_d());
    if(err != kDNSServiceErr_NoError) {
        qxt_d().state = Unknown;
        emit registrationError(err);
    } else {
        qxt_d().state = Registering;
        qxt_d().notifier = new QSocketNotifier(DNSServiceRefSockFD(qxt_d().service), QSocketNotifier::Read, this);
        QObject::connect(qxt_d().notifier, SIGNAL(activated(int)), &qxt_d(), SLOT(socketData()));
    }
}
Esempio n. 17
0
static void HandleEvents(void)
{
    int dns_sd_fd  = client  ? DNSServiceRefSockFD(client ) : -1;
    int dns_sd_fd2 = client2 ? DNSServiceRefSockFD(client2) : -1;
    int nfds = dns_sd_fd + 1;
    fd_set readfds;
    struct timeval tv;
    int result;

    if (dns_sd_fd2 > dns_sd_fd) nfds = dns_sd_fd2 + 1;

    while (!stopNow)
    {
        // 1. Set up the fd_set as usual here.
        // This example client has no file descriptors of its own,
        // but a real application would call FD_SET to add them to the set here
        FD_ZERO(&readfds);

        // 2. Add the fd for our client(s) to the fd_set
        if (client ) FD_SET(dns_sd_fd , &readfds);
        if (client2) FD_SET(dns_sd_fd2, &readfds);

        // 3. Set up the timeout.
        tv.tv_sec  = timeOut;
        tv.tv_usec = 0;

        result = select(nfds, &readfds, (fd_set*)NULL, (fd_set*)NULL, &tv);
        if (result > 0)
        {
            DNSServiceErrorType err = kDNSServiceErr_NoError;
            if      (client  && FD_ISSET(dns_sd_fd , &readfds)) err = DNSServiceProcessResult(client );
            else if (client2 && FD_ISSET(dns_sd_fd2, &readfds)) err = DNSServiceProcessResult(client2);
            if (err) {
                fprintf(stderr, "DNSServiceProcessResult returned %d\n", err);
                stopNow = 1;
            }
        }
        else if (result == 0)
            myTimerCallBack();
        else
        {
            printf("select() returned %d errno %d %s\n", result, errno, strerror(errno));
            if (errno != EINTR) stopNow = 1;
        }
    }
}
Esempio n. 18
0
//===========================================================================================================================
//	Stop
//===========================================================================================================================
void ExplorerBarWindow::Stop( DNSServiceRef ref )
{
	m_serviceRefs.remove( ref );

	WSAAsyncSelect(DNSServiceRefSockFD( ref ), m_hWnd, WM_PRIVATE_SERVICE_EVENT, 0);

	DNSServiceRefDeallocate( ref );
}
Esempio n. 19
0
int main(int argc, char **argv)
{
  struct dummy_struct ds;
  int c;
  int type = kDNSServiceType_ANY;
  int flags = 0;
  int ifindex = 0;

  memset (&ds, 0, sizeof(ds));
  while ((c = getopt(argc, argv, "f:t:i:")) != -1)
    switch (c)
      {
      case 't':
        type = atoi(optarg);
        break;
      case 'i':
        ifindex = if_nametoindex(optarg);
        break;
      case 'f':
        flags = atoi(optarg);
        break;
      }
  if (argc <= 1)
    {
      fprintf(stderr, "Usage: %s [-f <flags>] [-i <if>] [-t <type>] <name>\n",
              argv[0]);
      exit(1);
    }
  if (DNSServiceQueryRecord(&ds.service, flags, ifindex,
                            argv[1],
                            type,
                            kDNSServiceClass_IN,
                            dummy_callback,
                            NULL) != kDNSServiceErr_NoError)
    {
      fprintf(stderr, "Error initializing DNSServiceQueryRecord\n");
      exit(1);
    }

  if (uloop_init() < 0)
    {
      fprintf(stderr, "Error in uloop_init\n");
      exit(1);
    }
  ds.ufd.fd = DNSServiceRefSockFD(ds.service);
  printf("FD:%d\n", ds.ufd.fd);
  ds.ufd.cb = uloop_fd_callback;
  if (uloop_fd_add(&ds.ufd, ULOOP_READ) < 0)
    {
      fprintf(stderr, "Error in uloop_fd_add\n");
      exit(1);
    }
  printf("Entering event loop\n");
  uloop_run();
  return 0;
}
Esempio n. 20
0
bool
ServiceRef::SetSocketFlags() {
    return true;
#if 0 // XXX I think IOWatcher does the right thing. TODO: check!
  int fd = DNSServiceRefSockFD(ref_);
  if (fd == -1) return false;
  return fcntl(fd, F_SETFD, FD_CLOEXEC) != -1 &&
    fcntl(fd, F_SETFL, O_NONBLOCK) != -1;
#endif
}
Esempio n. 21
0
static void do_smb_resolve(struct mdns_smbsrv_result *browsesrv)
{
	DNSServiceRef mdns_conn_sdref = NULL;
	int mdnsfd;
	int fdsetsz;
	int ret;
	fd_set *fdset = NULL;
	struct timeval tv;
	DNSServiceErrorType err;

	TALLOC_CTX * ctx = talloc_tos();

	err = DNSServiceResolve(&mdns_conn_sdref, 0 /* flags */,
		browsesrv->ifIndex,
		browsesrv->serviceName, browsesrv->regType, browsesrv->domain,
		do_smb_resolve_reply, NULL);

	if (err != kDNSServiceErr_NoError) {
		return;
	}

	mdnsfd = DNSServiceRefSockFD(mdns_conn_sdref);
	for (;;)  {
		if (fdset != NULL) {
			TALLOC_FREE(fdset);
		}

		if (mdnsfd < 0 || mdnsfd >= FD_SETSIZE) {
			errno = EBADF;
			break;
		}

		fdsetsz = howmany(mdnsfd + 1, NFDBITS) * sizeof(fd_mask);
		fdset = TALLOC_ZERO(ctx, fdsetsz);
		FD_SET(mdnsfd, fdset);

		tv.tv_sec = 1;
		tv.tv_usec = 0;

		/* Wait until response received from mDNS daemon */
		ret = sys_select(mdnsfd + 1, fdset, NULL, NULL, &tv);
		if (ret <= 0 && errno != EINTR) {
			break;
		}

		if (FD_ISSET(mdnsfd, fdset)) {
			/* Invoke callback function */
			DNSServiceProcessResult(mdns_conn_sdref);
			break;
		}
	}

	TALLOC_FREE(fdset);
	DNSServiceRefDeallocate(mdns_conn_sdref);
}
Esempio n. 22
0
    void handleEvents_( DNSServiceRef service, const int32_t timeout = -1 )
    {
        assert( service );
        if( !service )
            return;

        const int fd = DNSServiceRefSockFD( service );
        const int nfds = fd + 1;

        while( !handled_ )
        {
            fd_set fdSet;
            FD_ZERO( &fdSet );
            FD_SET( fd, &fdSet );

            struct timeval tv;
            tv.tv_sec = timeout / 1000;
            tv.tv_usec = (timeout % 1000) * 1000;

            const int result = ::select( nfds, &fdSet, 0, 0,
                                         timeout < 0 ? 0 : &tv );
            switch( result )
            {
              case 0: // timeout
                return;

              case -1: // error
                LBWARN << "Select error: " << strerror( errno ) << " ("
                          << errno << ")" << std::endl;
                if( errno != EINTR )
                {
                    withdraw();
                    handled_ = true;
                }
                break;

              default:
                if( FD_ISSET( fd, &fdSet ))
                {
                    const DNSServiceErrorType error =
                        DNSServiceProcessResult( service );

                    if( error != kDNSServiceErr_NoError )
                    {
                        LBWARN << "DNSServiceProcessResult error: " << error
                               << std::endl;
                        withdraw();
                        handled_ = true;
                    }
                }
                break;
            }
        }
        handled_ = false;
    }
Esempio n. 23
0
CZeroconfBrowserWIN::~CZeroconfBrowserWIN()
{
  CSingleLock lock(m_data_guard);
  //make sure there are no browsers anymore
  for(tBrowserMap::iterator it = m_service_browsers.begin(); it != m_service_browsers.end(); ++it )
    doRemoveServiceType(it->first);

  WSAAsyncSelect( (SOCKET) DNSServiceRefSockFD( m_browser ), g_hWnd, BONJOUR_BROWSER_EVENT, 0 );
  DNSServiceRefDeallocate(m_browser);
  m_browser = NULL;
}
Esempio n. 24
0
int
browse(void)
{
	DNSServiceErrorType err;
	CFSocketContext ctx = { 0, NULL, NULL, NULL, NULL };

	err = DNSServiceBrowse(&nfsinfo.sdref, 0, 0, "_nfs._tcp", NULL, browser_callback, NULL);
	if (err != kDNSServiceErr_NoError)
		return (1);
	ctx.info = (void*)&nfsinfo;
	nfsinfo.sockref = CFSocketCreateWithNative(kCFAllocatorDefault, DNSServiceRefSockFD(nfsinfo.sdref),
			kCFSocketReadCallBack, socket_callback, &ctx);
	if (!nfsinfo.sockref)
		return (1);
	nfsinfo.rls = CFSocketCreateRunLoopSource(kCFAllocatorDefault, nfsinfo.sockref, 1);
	CFRunLoopAddSource(CFRunLoopGetCurrent(), nfsinfo.rls, kCFRunLoopDefaultMode);

	/* For backwards compatibility, browse for "mountd" services too */
	err = DNSServiceBrowse(&mountdinfo.sdref, 0, 0, "_mountd._tcp", NULL, browser_callback, NULL);
	if (err != kDNSServiceErr_NoError)
		return (1);
	ctx.info = (void*)&mountdinfo;
	mountdinfo.sockref = CFSocketCreateWithNative(kCFAllocatorDefault, DNSServiceRefSockFD(mountdinfo.sdref),
			kCFSocketReadCallBack, socket_callback, &ctx);
	if (!mountdinfo.sockref)
		return (1);
	mountdinfo.rls = CFSocketCreateRunLoopSource(kCFAllocatorDefault, mountdinfo.sockref, 1);
	CFRunLoopAddSource(CFRunLoopGetCurrent(), mountdinfo.rls, kCFRunLoopDefaultMode);

	CFRunLoopRun();

	CFRelease(nfsinfo.rls);
	CFSocketInvalidate(nfsinfo.sockref);
	CFRelease(nfsinfo.sockref);
	DNSServiceRefDeallocate(nfsinfo.sdref);
	CFRelease(mountdinfo.rls);
	CFSocketInvalidate(mountdinfo.sockref);
	CFRelease(mountdinfo.sockref);
	DNSServiceRefDeallocate(mountdinfo.sdref);
	return (0);
}
Esempio n. 25
0
static void stop(ErlDrvData edd) {
  dnssd_drv_t* dd = (dnssd_drv_t*) edd;
#ifdef __WIN32__
  if (dd->event) {
    driver_select(dd->erl_port, dd->event, DO_READ, 0);
    WSAEventSelect(DNSServiceRefSockFD(dd->sd_ref), NULL, 0);
  }
  if (dd->sd_ref) {
    DNSServiceRefDeallocate(dd->sd_ref);
  }
#else
  if (dd->sd_ref) {
    driver_select(dd->erl_port,
		  (ErlDrvEvent)(size_t) DNSServiceRefSockFD(dd->sd_ref),
		  DO_READ,
		  0);
    DNSServiceRefDeallocate(dd->sd_ref);
  }
#endif
  driver_free(dd);
}
Esempio n. 26
0
/*
 * Handle newly-discovered services
 */
static void
browser_callback(
	__unused DNSServiceRef sdRef,
	DNSServiceFlags servFlags,
	uint32_t interfaceIndex,
	DNSServiceErrorType errorCode,
	const char *serviceName,
	const char *regType,
	const char *replyDomain,
	__unused void *context)
{
	DNSServiceErrorType err;
	CFSocketContext ctx = { 0, NULL, NULL, NULL, NULL };
	struct cbinfo *info;

        if (errorCode != kDNSServiceErr_NoError) {
		printf("DNS service discovery error: %d\n", errorCode);
		return;
	}
#ifdef DEBUG
	printf("browse: %s: %s, %s, %s\n",
		(servFlags & kDNSServiceFlagsAdd) ? "new" : "gone",
		serviceName, regType, replyDomain);
#endif
	if (!(servFlags & kDNSServiceFlagsAdd))
		return;

	info = malloc(sizeof(*info));
	if (!info) {
		printf("browse: out of memeory\n");
		return;
	}

	err = DNSServiceResolve(&info->sdref, servFlags, interfaceIndex, serviceName, regType, replyDomain, resolve_callback, info);
	if (err != kDNSServiceErr_NoError) {
		printf("DNSServiceResolve failed: %d\n", err);
		free(info);
		return;
	}
	ctx.info = (void*)info;
	info->sockref = CFSocketCreateWithNative(kCFAllocatorDefault, DNSServiceRefSockFD(info->sdref),
				kCFSocketReadCallBack, socket_callback, &ctx);
	if (!info->sockref) {
		printf("CFSocketCreateWithNative failed\n");
		DNSServiceRefDeallocate(info->sdref);
		free(info);
		return;
	}
	info->rls = CFSocketCreateRunLoopSource(kCFAllocatorDefault, info->sockref, 1);
	CFRunLoopAddSource(CFRunLoopGetCurrent(), info->rls, kCFRunLoopDefaultMode);
}
Esempio n. 27
0
OSStatus
CSecondPage::StartOperation( DNSServiceRef ref )
{
	OSStatus err;

	err = WSAAsyncSelect((SOCKET) DNSServiceRefSockFD(ref), m_hWnd, WM_SERVICE_EVENT, FD_READ|FD_CLOSE);
	require_noerr( err, exit );

	m_serviceRefList.push_back( ref );

exit:

	return err;
}
Esempio n. 28
0
OSStatus
CPrinterSetupWizardSheet::StartOperation( DNSServiceRef ref )
{
	OSStatus err;

	err = WSAAsyncSelect((SOCKET) DNSServiceRefSockFD(ref), m_hWnd, WM_SOCKET_EVENT, FD_READ|FD_CLOSE);
	require_noerr( err, exit );

	m_serviceRefList.push_back( ref );

exit:

	return err;
}
Esempio n. 29
0
/*! @brief Starts the resolving service. Effectively, onResolveResults is called sometime later when the resolve is completed.
 
 		   This is done using a QSocketNotifer to monitor activity on the socket used by the DNSServiceResolve.
           When activity is observe DNSServiceProcessResult is called, which in turn calls the onResolveResults
 	
 	@param iface
 	@param name
 	@param type
 	@param domain
 */
void BonjourServiceResolver::startServiceResolve(uint32_t iface, const char* name, const char* type, const char* domain)
{
    DNSServiceErrorType err = DNSServiceResolve(&m_ref, 0, iface, name, type, domain, onResolveResults, this);
    if (err != kDNSServiceErr_NoError)
        debug << "BonjourServiceResolver::startServiceResolve. DNSServiceResolve failed for " << name << " " << type << endl;
    else
    {
        m_sockfd = DNSServiceRefSockFD(m_ref);
        if (m_sockfd != -1)
        {	// setup a notifier to call onResolveSocketRead every time the socket is read
            m_notifier = new QSocketNotifier(m_sockfd, QSocketNotifier::Read, this);
            connect(m_notifier, SIGNAL(activated(int)), this, SLOT(onSocketRead()));
        }
    }
LRESULT
CConfigPropertySheet::OnDataReady(WPARAM inWParam, LPARAM inLParam)
{
	if (WSAGETSELECTERROR(inLParam) && !(HIWORD(inLParam)))
	{
		dlog( kDebugLevelError, "OnSocket: window error\n" );
	}
	else
	{
		SOCKET sock = (SOCKET) inWParam;

		if ( m_browseDomainsRef && DNSServiceRefSockFD( m_browseDomainsRef ) == (int) sock )
		{
			DNSServiceProcessResult( m_browseDomainsRef );
		}
		else if ( m_regDomainsRef && DNSServiceRefSockFD( m_regDomainsRef ) == (int) sock )
		{
			DNSServiceProcessResult( m_regDomainsRef );
		}
	}

	return 0;
}