示例#1
0
文件: recvwall.c 项目: jadm1/bs
int client(char* host_address, int host_port, FILE* fin, FILE* fout, int buf_size) {
	int ret = 0;
	int socket_c;

	ret = socktcp(&socket_c);
	if (ret < 0) {
		return -1;
	}

	printf("Connection to %s:%d\n", host_address, host_port);

	ret = sockconnect(socket_c, host_address, host_port);
	if (ret < 0) {
		printf("connect() failed !\n");
		sockclose(socket_c);
		return -1;
	}
	printf("Connection successful !\n");

	ret = sender(socket_c, fin, fout, buf_size);

	printf("Disconnecting...\n");

	sockclose(socket_c);

	return ret;
}
示例#2
0
void SocketBase::close()
{
    if (fd != -1){
        sockclose(fd);
        fd = -1;
    }
}
示例#3
0
bool ASE::SetPortEnabled ( bool bInternetEnabled, bool bLanEnabled )
{
    // Calc requirements
    bool bPortEnableReq = bInternetEnabled || bLanEnabled;
    bool bLanOnly = !bInternetEnabled && bLanEnabled;
    ushort usPortReq = m_usPortBase + SERVER_LIST_QUERY_PORT_OFFSET;

    // Any change?
    if ( ( m_Socket != INVALID_SOCKET ) == bPortEnableReq && m_usPort == usPortReq )
        return true;

    m_usPort = usPortReq;

    // Remove current thingmy
    if ( m_Socket != INVALID_SOCKET )
    {
        closesocket( m_Socket );
        m_Socket = INVALID_SOCKET;
    }

    if ( !bPortEnableReq )
        return true;

    // Start new thingmy
    m_SockAddr.sin_family = AF_INET;         
    m_SockAddr.sin_port = htons ( m_usPort );
    // If a local IP has been specified, ensure it is used for sending
    if ( m_strIP.length () )
        m_SockAddr.sin_addr.s_addr = inet_addr( m_strIP.c_str () );
    else
        m_SockAddr.sin_addr.s_addr = INADDR_ANY;

    // Initialize socket
    m_Socket = socket ( AF_INET, SOCK_DGRAM, 0 );

    // If we are in lan only mode, reuse addr to avoid possible conflicts
    if ( bLanOnly )
    {
        const int Flags = 1;
        setsockopt ( m_Socket, SOL_SOCKET, SO_REUSEADDR, (const char *)&Flags, sizeof ( Flags ) );
    }

    // Bind the socket
    if ( bind ( m_Socket, ( sockaddr* ) &m_SockAddr, sizeof ( m_SockAddr ) ) != 0 )
    {
        sockclose ( m_Socket );
        m_Socket = INVALID_SOCKET;
        return false;
    }

    // Set it to non blocking, so we dont have to wait for a packet
    #ifdef WIN32
    unsigned long ulNonBlock = 1;
    ioctlsocket ( m_Socket, FIONBIO, &ulNonBlock );
    #else
    fcntl ( m_Socket, F_SETFL, fcntl( m_Socket, F_GETFL ) | O_NONBLOCK ); 
    #endif

    return true;
}
示例#4
0
int ntq_connect(ntq_server** pserver, char* server_address, int server_port) {
	int ret = 0;
	ntq_server* server = NULL;

	server = (ntq_server*)malloc(sizeof(ntq_server));
	if (server == NULL) {
		fprintf(stderr, "ntq_connect() error not enough memory\n");
		return -1;
	}

	server->server_address = server_address;
	server->server_port = server_port;

	ret = socktcp(&server->socket);
	if (ret != 0) {
		fprintf(stderr, "ntq_connect() error socket creation failed\n");
		return -1;
	}
	ret = sockconnect(server->socket, server->server_address, server->server_port);
	if (ret != 0) {
		fprintf(stderr, "ntq_connect() error socket connect failed\n");
		sockclose(server->socket);
		return -1;
	}

	*pserver = server;
	return 0;
}
示例#5
0
static void RemoteClose (Connection *remo)
{
    sockclose (remo->sok);
    remo->sok = -1;
    remo->connect = 0;
    remo->open = &RemoteOpen;
    unlink (remo->server);
}
示例#6
0
ASE::ASE ( CMainConfig* pMainConfig, CPlayerManager* pPlayerManager, unsigned short usPort, const char* szServerIP, bool bLan )
{
    _instance = this;

    m_bLan = bLan;
    m_usPort = usPort + ( ( m_bLan ) ? SERVER_LIST_QUERY_PORT_OFFSET_LAN : SERVER_LIST_QUERY_PORT_OFFSET );

    m_pMainConfig = pMainConfig;
    m_pPlayerManager = pPlayerManager;

    m_strGameType = "MTA:SA";
    m_strMapName = "None";
    if ( szServerIP )
        m_strIP = szServerIP;
    std::stringstream ss;
    ss << usPort;
    m_strPort = ss.str();

    // Set the sock addr
    m_SockAddr.sin_family = AF_INET;         
    m_SockAddr.sin_port = htons ( m_usPort );
    // If a local IP has been specified, ensure it is used for sending
    if ( m_strIP.length () )
        m_SockAddr.sin_addr.s_addr = inet_addr( m_strIP.c_str () );
    else
        m_SockAddr.sin_addr.s_addr = INADDR_ANY;

    // Initialize socket
    m_Socket = socket ( AF_INET, SOCK_DGRAM, 0 );

    // If we are in lan only mode, reuse addr to avoid possible conflicts
    if ( m_bLan )
    {
        const int Flags = 1;
        setsockopt ( m_Socket, SOL_SOCKET, SO_REUSEADDR, (const char *)&Flags, sizeof ( Flags ) );
    }

    // Bind the socket
    if ( bind ( m_Socket, ( sockaddr* ) &m_SockAddr, sizeof ( m_SockAddr ) ) != 0 )
    {
        sockclose ( m_Socket );
        m_Socket = NULL;
        return;
    }

    // Set it to non blocking, so we dont have to wait for a packet
    #ifdef WIN32
    unsigned long ulNonBlock = 1;
    ioctlsocket ( m_Socket, FIONBIO, &ulNonBlock );
    #else
    fcntl ( m_Socket, F_SETFL, fcntl( m_Socket, F_GETFL ) | O_NONBLOCK ); 
    #endif
}
示例#7
0
int ntq_disconnect(ntq_server** pserver) {
	ntq_server* server = NULL;

	if (pserver == NULL) {
		return 0;
	}
	server = *pserver;


	sockclose(server->socket);

	free(server);
	server = NULL;
	*pserver = server;
	return 0;
}
示例#8
0
/**************************************************************************************************
	AXFR
	DNS-based zone transfer.  Send all resource records for in QNAME's zone to the client.
**************************************************************************************************/
void
axfr(TASK *t) {
#if DEBUG_ENABLED && DEBUG_AXFR
  struct timeval start = { 0, 0}, finish = { 0, 0 };	/* Time AXFR began and ended */
#endif
  MYDNS_SOA *soa = NULL;				/* SOA record for zone (may be bogus!) */

  /* Do generic startup stuff; this is a child process */
  signal(SIGALRM, axfr_timeout);
  alarm(AXFR_TIME_LIMIT);
  sql_close(sql);
  db_connect();

#if DEBUG_ENABLED && DEBUG_AXFR
  gettimeofday(&start, NULL);
  DebugX("axfr", 1,_("%s: Starting AXFR for task ID %u"), desctask(t), t->internal_id);
#endif
  total_records = total_octets = 0;
  t->no_markers = 1;

  /* Get SOA for zone */
  soa = axfr_get_soa(t);

  if (soa){
    /* Transfer that zone */
    axfr_zone(t, soa);
  }

#if DEBUG_ENABLED && DEBUG_AXFR
  /* Report result */
  gettimeofday(&finish, NULL);
  DebugX("axfr", 1,_("AXFR: %u records, %u octets, %.3fs"), 
	 (unsigned int)total_records, (unsigned int)total_octets,
	 ((finish.tv_sec + finish.tv_usec / 1000000.0) - (start.tv_sec + start.tv_usec / 1000000.0)));
#endif
  t->qdcount = 1;
  t->an.size = total_records;
  task_output_info(t, NULL);

  sockclose(t->fd);

  _exit(EXIT_SUCCESS);
}
示例#9
0
/* static void axfr_error(TASK *, const char *, ...) __attribute__ ((__noreturn__)); */
static void
axfr_error(TASK *t, const char *fmt, ...) {
  va_list	ap; 
  char		*msg = NULL;

  if (t) {
    task_output_info(t, NULL);
  } else {
    va_start(ap, fmt);
    VASPRINTF(&msg, fmt, ap);
    va_end(ap);

    Warnx("%s", msg);
    RELEASE(msg);
  }

  sockclose(t->fd);

  _exit(EXIT_FAILURE);
  /* NOTREACHED */
}
示例#10
0
/*
 * This is the main thread
 * Its role consists in accepting connections to the server,
 * and placing the new clients in a client queue where they will wait to
 * be processed by the manager threads
 */
int ntqserver(int verbose, char* address, int port, int n_queues, int n_managers) {
	int ret = 0;
	int i;
	ntqs_server* ntqs;
	ntqs_manager* managers;
	ntqs_manager* manager;
	pthread_mutex_t m_console_data;
	pthread_mutex_t m_clients_data;
	pthread_mutex_t* m_queues_array;
	pthread_mutex_t* m_interrupt_array;
	ntqs_client* client = NULL;


	printf("Starting server ...\n");

	ntqs = (ntqs_server*)malloc(sizeof(ntqs_server));
	if (ntqs == NULL) {
		fprintf(stderr, "ntqserver(): error not enough memory\n");
		return -1;
	}

	ntqs->verbose = verbose;
	/**
	 *  Verbosity parameter
	 */
	ntqs->host_address = address;
	/**
	 *  This is the address on which the server listens.
	 */
	ntqs->host_port = port;
	/**
	 *  This is the server port number
	 */
	ntqs->n_queues = n_queues;
	/**
	 *  This is the number of queues (specified by the -q parameter) that will be created and accessible
	 */
	ntqs->n_managers = n_managers;
	/*
	 *  This is the number of manager threads that can be created to process clients.
	 *  1 (the default value) should be sufficient in most cases.
	 *  A higher number may give some speed ups only if there are many connections and/or clients need to transmit a lot of data.
	 */
	ntqs->socket = 0;
	/**
	 *  This is the server main socket used for accepting connections only
	 */
	ntqs->m_console = NULL;
	/**
	 *  This is a console mutex used to prevent more than one thread at time from printing to the console
	 */
	ntqs->q_clients = NULL;
	/**
	 *  This is the client queue
	 *  The manager threads are regularly popping clients from the queue in order to process them
	 *  or pushing them back to the queue once they are done processing them.
	 *  New clients are added to the queue, and disconnecting clients leave the queue.
	 */
	ntqs->m_clients = NULL;
	/**
	 *  This mutex is there to allow only one manager at a time to interact with the client queue
	 */
	ntqs->m_queues = NULL;
	/*
	 *  All task queues are mutex protected so that only one manager can push or pop data from a given queue at a given time
	 */
	ntqs->queues = NULL;
	/**
	 *  This is the array of the n_queues task queues
	 */


	// creating client queue mutex
	ntqs->m_clients = &m_clients_data;
	ret = pthread_mutex_init(ntqs->m_clients, NULL);
	if (ret != 0) {
		fprintf(stderr, "ntqserver(): error mutex creation failed\n");
		return -1;
	}
	// creating client queue
	ret = llq_create(&ntqs->q_clients);
	if (ret != 0) {
		fprintf(stderr, "ntqserver(): error queue creation failed\n");
		return -1;
	}



	// creating queues mutexes
	ntqs->m_queues = (pthread_mutex_t**)malloc(ntqs->n_queues * sizeof(pthread_mutex_t*));
	if (ntqs->m_queues == NULL) {
		fprintf(stderr, "ntqserver(): error not enough memory\n");
		return -1;
	}
	m_queues_array = (pthread_mutex_t*)malloc(ntqs->n_queues * sizeof(pthread_mutex_t));
	if (m_queues_array == NULL) {
		fprintf(stderr, "ntqserver(): error not enough memory\n");
		return -1;
	}
	for (i = 0; i < ntqs->n_queues; i++) {
		ntqs->m_queues[i] = &m_queues_array[i];
		ret = pthread_mutex_init(ntqs->m_queues[i], NULL);
		if (ret != 0) {
			fprintf(stderr, "ntqserver(): error mutex creation failed\n");
			return -1;
		}
	}
	// creating queues
	ntqs->queues = (llq**)malloc(ntqs->n_queues * sizeof(llq*));
	if (ntqs->queues == NULL) {
		fprintf(stderr, "ntqserver(): error not enough memory\n");
		return -1;
	}
	for (i = 0; i < ntqs->n_queues; i++) {
		ret = llq_create(&ntqs->queues[i]);
		if (ret != 0) {
			fprintf(stderr, "ntqserver(): error queue creation failed\n");
			return -1;
		}
	}


	/**
	 * Create a server socket
	 */
	ret = socktcp(&ntqs->socket);
	if (ret < 0) {
		fprintf(stderr, "ntqserver(): error socket creation failed\n");
		return -1;
	}

	/**
	 * Bind and listen
	 */
	ret = socklisten(ntqs->socket, ntqs->host_address, ntqs->host_port, 10);
	if (ret < 0) {
		fprintf(stderr, "ntqserver(): error socket listen failed\n");
		return -1;
	}

	printf("Listening on %s:%d ...\n", ntqs->host_address, ntqs->host_port);


	printf("Starting manager(s) ...\n");
	// setup multithreading

	// create console mutex
	ntqs->m_console = &m_console_data;
	ret = pthread_mutex_init(ntqs->m_console, NULL);
	if (ret != 0) {
		fprintf(stderr, "ntqserver(): error console mutex creation failed\n");
		return -1;
	}

	// create interrupt mutexes array
	m_interrupt_array = (pthread_mutex_t*)malloc(ntqs->n_managers*sizeof(pthread_mutex_t));
	if (m_interrupt_array == NULL) {
		pthread_mutex_lock(ntqs->m_console);
		fprintf(stderr, "ntqserver(): error not enough memory\n");
		pthread_mutex_unlock(ntqs->m_console);
		return -1;
	}


	// create managers
	managers = (ntqs_manager*)malloc(ntqs->n_managers*sizeof(ntqs_manager));
	if (managers == NULL) {
		pthread_mutex_lock(ntqs->m_console);
		fprintf(stderr, "ntqserver(): error not enough memory\n");
		pthread_mutex_unlock(ntqs->m_console);
		return -1;
	}


	for (i = 0; i < ntqs->n_managers; i++) {
		manager = &managers[i];
		manager->ntqs = ntqs;
		manager->id = i;
		manager->m_interrupt = &m_interrupt_array[i];
		manager->interrupt = 0;

		ret = pthread_mutex_init(manager->m_interrupt, NULL);
		if (ret != 0) {
			pthread_mutex_lock(ntqs->m_console);
			fprintf(stderr, "ntqserver(): error interrupt mutex creation failed\n");
			pthread_mutex_unlock(ntqs->m_console);
			return -1;
		}

		/**
		 *  Start a manager thread
		 */
		ret = pthread_create(&manager->thread, NULL, &ntqmanagerwrapper, (void*)manager);
		if (ret != 0) {
			pthread_mutex_lock(ntqs->m_console);
			fprintf(stderr, "ntqserver(): error thread creation failed\n");
			pthread_mutex_unlock(ntqs->m_console);
			return -1;
		}
	}


	pthread_mutex_lock(ntqs->m_console);
	printf("Accepting connections ...\n");
	pthread_mutex_unlock(ntqs->m_console);

	while (1) {
		pthread_mutex_lock(ntqs->m_console);
		fflush(stderr);
		fflush(stdout);
		pthread_mutex_unlock(ntqs->m_console);

		// create new client data structure
		client = (ntqs_client*)malloc(sizeof(ntqs_client));
		if (client == NULL) {
			pthread_mutex_lock(ntqs->m_console);
			fprintf(stderr, "ntqserver(): error not enough memory\n");
			pthread_mutex_unlock(ntqs->m_console);
			return -1;
		}

		// check for server socket activity
		ret = sockreadable(ntqs->socket);
		if (ret < 0) {
			pthread_mutex_lock(ntqs->m_console);
			fprintf(stderr, "ntqserver(): error socket accept failed\n");
			pthread_mutex_unlock(ntqs->m_console);
			return -1;
		}

		if (ret == 0) {
			// socket idle (no new connection received)
			UTLsleep(10); // nothing to do so go to sleep
			// check for interrupt signal after sleeping (likely to happen while sleeping)
			if (signal_interrupt) {
				break;
			}
		}
		else {
			// activity on socket -> accept new connection and write to the client data structure
			ret = sockaccept(ntqs->socket, &client->socket, client->remote_ip, &client->remote_port);
			if (ret < 0) {
				pthread_mutex_lock(ntqs->m_console);
				fprintf(stderr, "ntqserver(): error socket accept failed\n");
				pthread_mutex_unlock(ntqs->m_console);
				return -1;
			}

			pthread_mutex_lock(ntqs->m_console);
			printf("%s:%d connected\n", client->remote_ip, client->remote_port);
			pthread_mutex_unlock(ntqs->m_console);


			//pthread_mutex_lock(ntqs->m_console);
			//printf("%s:%d in queue\n", client->remote_ip, client->remote_port);
			//pthread_mutex_unlock(ntqs->m_console);

			// from there on the client data becomes the property of the manager (unavalaible from the main thread)
			pthread_mutex_lock(ntqs->m_clients);
			llq_push(ntqs->q_clients, (void*)client);
			pthread_mutex_unlock(ntqs->m_clients);
		}
	}


	pthread_mutex_lock(ntqs->m_console);
	printf("Stopping server ...\n");
	pthread_mutex_unlock(ntqs->m_console);

	if (signal_interrupt) {
		/*
		 * Send interrupt signal to all the manager threads.
		 */
		for (i = 0; i < ntqs->n_managers; i++) {
			manager = &managers[i];
			pthread_mutex_lock(manager->m_interrupt);
			manager->interrupt = 1;
			pthread_mutex_unlock(manager->m_interrupt);
		}
	}


	/**
	 * Wait for threads to end
	 */
	for (i = 0; i < ntqs->n_managers; i++) {
		manager = &managers[i];
		ret = pthread_join(manager->thread, NULL);
		ret = pthread_mutex_destroy(manager->m_interrupt);
	}

	/**
	 * Free all data
	 */

	free((void*)managers);
	free((void*)m_interrupt_array);
	ret = pthread_mutex_destroy(ntqs->m_console);
	for (i = 0; i < ntqs->n_queues; i++) {
		while (!llq_isempty(ntqs->queues[i])) {
			free(llq_pop(ntqs->queues[i]));
		}
		llq_delete(&ntqs->queues[i]);
		ret = pthread_mutex_destroy(ntqs->m_queues[i]);
	}
	free((void*)m_queues_array);
	free((void*)ntqs->queues);
	while (!llq_isempty(ntqs->q_clients)) {
		client = (ntqs_client*)llq_pop(ntqs->q_clients);
		sockclose(client->socket);
		free(client);
	}
	sockclose(ntqs->socket);
	free((void*)ntqs->m_queues);
	llq_delete(&ntqs->q_clients);
	ret = pthread_mutex_destroy(ntqs->m_clients);

	free((void*)ntqs);

	return 0;
}
示例#11
0
文件: ASE.cpp 项目: ccw808/mtasa-blue
bool ASE::SetPortEnabled(bool bInternetEnabled, bool bLanEnabled)
{
    // Calc requirements
    bool   bPortEnableReq = bInternetEnabled || bLanEnabled;
    bool   bLanOnly = !bInternetEnabled && bLanEnabled;
    ushort usPortReq = m_usPortBase + SERVER_LIST_QUERY_PORT_OFFSET;

    // Any change?
    if ((!m_SocketList.empty()) == bPortEnableReq && m_usPort == usPortReq)
        return true;

    m_usPort = usPortReq;

    // Remove current thingmy
    for (uint s = 0; s < m_SocketList.size(); s++)
    {
        closesocket(m_SocketList[s]);
    }
    m_SocketList.clear();

    if (!bPortEnableReq)
        return true;

    // Start new thingmy
    // If a local IP has been specified, ensure it is used for sending
    std::vector<SString> ipList;
    m_strIPList.Split(",", ipList);
    for (uint i = 0; i < ipList.size(); i++)
    {
        const SString& strIP = ipList[i];
        sockaddr_in    sockAddr;
        sockAddr.sin_family = AF_INET;
        sockAddr.sin_port = htons(m_usPort);
        if (!strIP.empty())
            sockAddr.sin_addr.s_addr = inet_addr(strIP);
        else
            sockAddr.sin_addr.s_addr = INADDR_ANY;

        // Initialize socket
        SOCKET newSocket = socket(AF_INET, SOCK_DGRAM, 0);

        // If we are in lan only mode, reuse addr to avoid possible conflicts
        if (bLanOnly)
        {
            const int Flags = 1;
            setsockopt(newSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&Flags, sizeof(Flags));
        }

        // Bind the socket
        if (::bind(newSocket, (sockaddr*)&sockAddr, sizeof(sockAddr)) != 0)
        {
            sockclose(newSocket);
            newSocket = INVALID_SOCKET;
            return false;
        }

        // Set it to non blocking, so we dont have to wait for a packet
        #ifdef WIN32
        unsigned long ulNonBlock = 1;
        ioctlsocket(newSocket, FIONBIO, &ulNonBlock);
        #else
        fcntl(newSocket, F_SETFL, fcntl(newSocket, F_GETFL) | O_NONBLOCK);
        #endif

        m_SocketList.push_back(newSocket);
    }

    return true;
}