Esempio n. 1
0
static int
init_fake_server(int ip_port)
{
	struct sockaddr_in sin;
	TDS_SYS_SOCKET s;

	memset(&sin, 0, sizeof(sin));
	sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
	sin.sin_port = htons((short) ip_port);
	sin.sin_family = AF_INET;

	if (TDS_IS_SOCKET_INVALID(s = socket(AF_INET, SOCK_STREAM, 0))) {
		perror("socket");
		exit(1);
	}
	if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
		perror("bind");
		CLOSESOCKET(s);
		return 1;
	}
	if (listen(s, 5) < 0) {
		perror("listen");
		CLOSESOCKET(s);
		return 1;
	}
	if (tds_thread_create(&fake_thread, fake_thread_proc, int2ptr(s)) != 0) {
		perror("tds_thread_create");
		exit(1);
	}
	return 0;
}
Esempio n. 2
0
void
tds_wakeup_close(TDSPOLLWAKEUP *wakeup)
{
	if (!TDS_IS_SOCKET_INVALID(wakeup->s_signal))
		CLOSESOCKET(wakeup->s_signal);
	if (!TDS_IS_SOCKET_INVALID(wakeup->s_signaled))
		CLOSESOCKET(wakeup->s_signaled);
}
Esempio n. 3
0
static int jiveL_dns_gc(lua_State *L) {
	struct dns_userdata *u;

	u = lua_touserdata(L, 1);
	CLOSESOCKET(u->fd[0]);
	CLOSESOCKET(u->fd[1]);

	return 0;
}
Esempio n. 4
0
void nv_get(const char *vid) {
	WS2I
	const char * const us = getSession();
	char * const buf = malloc(1024 * 1024);//1MB cache
	char *ptr, *host, *url;
	int sock = create_socket("www.nicovideo.jp", "http", 0), len;
	send(sock, "HEAD /watch/", 12, 0);
	send(sock, vid, strlen(vid), 0);
	send(sock, " HTTP/1.0\r\nHost: www.nicovideo.jp\r\nCookie: user_session=", 56, 0);
	send(sock, us, strlen(us), 0);
	send(sock, "\r\n\r\n", 4, 0);
	buf[recv(sock, buf, 1024 * 1024, MSG_WAITALL)] = 0;
	CLOSESOCKET(sock);
	ptr = strstr(buf, "nicohistory=") + 12; *strchr(ptr, ';') = 0;
	strcpy(buf + 1024 * 1023, ptr);
	// ---------------------------------------------------------------------------------
	sock = create_socket("flapi.nicovideo.jp", "http", 0);
	send(sock, "GET /api/getflv?v=", 18, 0);
	send(sock, vid, strlen(vid), 0);
	send(sock, " HTTP/1.0\r\nHost: flapi.nicovideo.jp\r\nCookie: user_session=", 58, 0);
	send(sock, us, strlen(us), 0);
	send(sock, "\r\n\r\n", 4, 0);
	buf[recv(sock, buf, 1024 * 1023, MSG_WAITALL)] = 0;
	CLOSESOCKET(sock);
	ptr = strstr(buf, "url=") + 4; *strchr(ptr, '&') = 0;
	sep_dec_url(ptr, &host, &url);
	// ---------------------------------------------------------------------------------
	sock = create_socket(host, ptr, 0);
	send(sock, "GET ", 4, 0);
	send(sock, url, strlen(url), 0);
	send(sock, " HTTP/1.0\r\nHost: ", 17, 0);
	send(sock, host, strlen(host), 0);
	send(sock, "\r\nCookie: nicohistory=", 22, 0);
	send(sock, buf + 1024 * 1023, strlen(buf + 1024 * 1023), 0);
	send(sock, "; user_session=", 15, 0);
	send(sock, us, strlen(us), 0);
	send(sock, "\r\n\r\n", 4, 0);
	memcpy(buf, CACHE_DIR, 6);
	strcpy(buf + 6, vid);
	FILE *f = fopen(buf, "wb");
	int http = 0;
	while ((len = recv(sock, buf, 1024 * 1024, MSG_WAITALL))) {
		ptr = buf; url = ptr + len;
		if (http >= 2) goto L2;
L1:		if (*ptr == '\n') { if (++http >= 2) { ptr++; goto L2; }
		} else if (*ptr != '\r') http = 0;
		if (++ptr < url) goto L1;
		continue;
L2:		fwrite(ptr, 1, url - ptr, f);
	}
	CLOSESOCKET(sock);
	fclose(f);
	WS2U
}
Esempio n. 5
0
void NetKeepaliveDestroy( void )
{
	shutdown(ka.keepalive_fd, SHUT_RDWR);

#ifdef WIN32
	if( hHandle != NULL )
  {
		IcmpCloseHandle(hHandle);
    hHandle = NULL;
  }

	if( hEvent != NULL )
  {
		CloseHandle(hEvent);
    hEvent = NULL;
  }

  // Free IP Helper API DLL handle, and invalidate function pointers.
  if( hndliphlp != NULL )
  {
    IcmpCreateFile      = NULL;
    IcmpCloseHandle     = NULL;
    IcmpSendEcho2       = NULL;
    IcmpParseReplies    = NULL;
    Icmp6CreateFile     = NULL;
    Icmp6SendEcho2      = NULL;
    Icmp6ParseReplies   = NULL;

    FreeLibrary( hndliphlp );
  }
#endif

	CLOSESOCKET(ka.keepalive_fd);
	memset(&ka, 0, sizeof(struct NetKeepAlive));
}
Esempio n. 6
0
/**
 * Close current socket
 * for last socket close entire connection
 * for MARS send FIN request
 */
void
tds_close_socket(TDSSOCKET * tds)
{
	if (!IS_TDSDEAD(tds)) {
#if ENABLE_ODBC_MARS
		TDSCONNECTION *conn = tds->conn;
		unsigned n = 0, count = 0;
		tds_mutex_lock(&conn->list_mtx);
		for (; n < conn->num_sessions; ++n)
			if (TDSSOCKET_VALID(conn->sessions[n]))
				++count;
		if (count > 1)
			tds_append_fin(tds);
		tds_mutex_unlock(&conn->list_mtx);
		if (count <= 1) {
			tds_disconnect(tds);
			tds_connection_close(conn);
		} else {
			tds_set_state(tds, TDS_DEAD);
		}
#else
		tds_disconnect(tds);
		if (CLOSESOCKET(tds_get_s(tds)) == -1)
			tdserror(tds_get_ctx(tds), tds,  TDSECLOS, sock_errno);
		tds_set_s(tds, INVALID_SOCKET);
		tds_set_state(tds, TDS_DEAD);
#endif
	}
}
Esempio n. 7
0
/* read bytes from the streaming socket and discard - used by network test to measure network throughput*/
static int stream_readtonullL(lua_State *L) {
	struct stream *stream;
	char buf[4094];
	int n;
	/*
	 * 1: Stream (self)
	 */

	stream = lua_touserdata(L, 1);

	n = recv(stream->fd, buf, sizeof(buf), 0);	

	if (n > 0) {
		fifo_lock(&streambuf_fifo);
		streambuf_bytes_received += n;
		fifo_unlock(&streambuf_fifo);
		lua_pushinteger(L, n);
		return 1;
	} else if (n == -1 && errno == EAGAIN) {
		lua_pushinteger(L, 0);
		return 1;
	} else {
		CLOSESOCKET(stream->fd);
		lua_pushnil(L);
		lua_pushstring(L, strerror(n));
		return 2;
	}
}
Esempio n. 8
0
/* read data from the stream socket into a lua string */
static int stream_readtoL(lua_State *L) {
	struct stream *stream;
	char buf[4094];
	int n;
	/*
	 * 1: Stream (self)
	 */

	stream = lua_touserdata(L, 1);

	n = recv(stream->fd, buf, sizeof(buf), 0);	

	if (n > 0) {
		lua_pushlstring(L, buf, n);
		return 1;
	} else if (n == -1 && errno == EAGAIN) {
		lua_pushnil(L);
		return 1;
	} else {
		CLOSESOCKET(stream->fd);
		lua_pushnil(L);
		lua_pushstring(L, strerror(SOCKETERROR));
		return 2;
	}
}
Esempio n. 9
0
/* remove all pollfunctions and close socket */
static void udpreceive_tilde_closesocket(t_udpreceive_tilde* x)
{
    sys_rmpollfn(x->x_socket);
    outlet_float(x->x_outlet1, 0);
    CLOSESOCKET(x->x_socket);
    x->x_socket = -1;
}
Esempio n. 10
0
static void *http_thread(void *ptr) {
	slimaudio_t *audio = (slimaudio_t *) ptr;
#ifdef SLIMPROTO_DEBUG				
	int last_state = 0;
#endif

#ifdef BSD_THREAD_LOCKING
	pthread_mutex_lock(&audio->http_mutex);
#endif

	audio->http_state = STREAM_STOPPED;
	
	while (true) {
				
#ifdef SLIMPROTO_DEBUG				
		if (last_state == audio->http_state) {
			VDEBUGF("http_thread state %i\n", audio->http_state);
		}
		else {
			DEBUGF("http_thread state %i\n", audio->http_state);
		}
			
		last_state = audio->http_state;
#endif

		switch (audio->http_state) {
			case STREAM_STOP:
				CLOSESOCKET(audio->streamfd);
				slimproto_dsco(audio->proto, DSCO_CLOSED);

				slimaudio_buffer_close(audio->decoder_buffer);
				
				audio->http_state = STREAM_STOPPED;

				pthread_cond_broadcast(&audio->http_cond);

				break;
				
			case STREAM_STOPPED:
				pthread_cond_wait(&audio->http_cond, &audio->http_mutex);
				break;
			
			case STREAM_PLAYING:
				pthread_mutex_unlock(&audio->http_mutex);
				
				http_recv(audio);
				
				pthread_mutex_lock(&audio->http_mutex);

				break;
				
			case STREAM_QUIT:
				return 0;
		}
	}
		
	pthread_mutex_unlock(&audio->http_mutex);
}
Esempio n. 11
0
static void
pool_destroy(TDS_POOL *pool)
{
	pool_mbr_destroy(pool);
	pool_user_destroy(pool);

	CLOSESOCKET(pool->wakeup_fd);
	CLOSESOCKET(pool->listen_fd);
	CLOSESOCKET(pool->event_fd);
	tds_mutex_free(&pool->events_mtx);

	free(pool->user);
	free(pool->password);
	free(pool->server);
	free(pool->database);
	free(pool->name);
	free(pool);
}
bool CG_NetSocket::Close()
{
	if (m_socket == INVALID_SOCKET) return false;
	CLOSESOCKET(m_socket);
	Reset();
	if (--m_nCount==0)
		_NetCleanUp();
	return true;
}
Esempio n. 13
0
/*
====================
 dis-connection client fd
====================
*/
void disconnectClient (struct sPacket* pClient)
{
    REMOVE_FROM_LIST (g_ClientList, pClient, m_prev, m_next);
    if (pClient->m_sock != INVALID_SOCKET)
        CLOSESOCKET (pClient->m_sock);

    free (pClient);
    pClient = NULL;
}
Esempio n. 14
0
int
tds_close_socket(TDSSOCKET * tds)
{
	int rc = -1;

	if (!IS_TDSDEAD(tds)) {
		rc = CLOSESOCKET(tds->s);
		tds->s = INVALID_SOCKET;
		tds_set_state(tds, TDS_DEAD);
	}
	return rc;
}
Esempio n. 15
0
/* accept a socket and read data as much as you can */
static TDS_THREAD_PROC_DECLARE(fake_thread_proc, arg)
{
	TDS_SYS_SOCKET s = ptr2int(arg), sock;
	socklen_t len;
	char buf[128];
	struct sockaddr_in sin;
	struct pollfd fd;

	memset(&sin, 0, sizeof(sin));
	len = sizeof(sin);

	fd.fd = s;
	fd.events = POLLIN;
	fd.revents = 0;
	if (poll(&fd, 1, 30000) <= 0) {
		perror("poll");
		exit(1);
	}

	if (TDS_IS_SOCKET_INVALID(sock = tds_accept(s, (struct sockaddr *) &sin, &len))) {
		perror("accept");
		exit(1);
	}
	tds_mutex_lock(&mtx);
	fake_sock = sock;
	tds_mutex_unlock(&mtx);
	CLOSESOCKET(s);

	for (;;) {
		int len;

		fd.fd = sock;
		fd.events = POLLIN;
		fd.revents = 0;
		if (poll(&fd, 1, 30000) <= 0) {
			perror("poll");
			exit(1);
		}

		/* just read and discard */
		len = READSOCKET(sock, buf, sizeof(buf));
		if (len == 0)
			break;
		if (len < 0 && sock_errno != TDSSOCK_EINPROGRESS)
			break;
	}
	return NULL;
}
Esempio n. 16
0
/*
====================
 acppet a new client fd
====================
*/
void acceptNewClient (SOCKET listenfd)
{
    SOCKET newDesc;
    struct sockaddr_in peer;
#if defined (WIN32)
    int peersize;
#else
    socklen_t peersize;
#endif

    peersize = sizeof (peer);
    newDesc = accept (listenfd, (struct sockaddr*) &peer, &peersize);
    if (newDesc < 0)
    {
        outLog ((char*)"accept new client failed!\r\n");
        return;
    }
    setNonblock (newDesc);

    struct sPacket* newClient = (struct sPacket*) malloc (sizeof (struct sPacket*));

    if (!newClient)
    {
        CLOSESOCKET (newDesc);
        return;
    }

    newClient->m_sock = newDesc;
    (void*) strcpy (newClient->m_ip, (char*) inet_ntoa (peer.sin_addr));

    *newClient->m_recvBuff = 0x00;
     newClient->m_recvSize = 0x00;
     newClient->m_recvPos  = 0x00;

    *newClient->m_sendBuff = 0x00;
     newClient->m_sendSize = 0x00;
 
    *newClient->m_name     = 0x00;
     newClient->m_lastRecvTime = getTime ();

    newClient->m_prev = NULL;
    newClient->m_next = NULL;

    INSERT_TO_LIST (g_ClientList, newClient, m_prev, m_next);
    g_TotalClient++;
    outLog ((char*)"accept new connection: %d [%s]\r\n", newDesc, newClient->m_ip);
}
Esempio n. 17
0
File: HTran.cpp Progetto: bGN4/HTran
void closeallfd() {
    int i;

    printf("[+] Let me exit ......\r\n");
    fflush(stdout);

    for (i = 3; i < 256; i++) {
        CLOSESOCKET(i);
    }

    if (fp != NULL) {
        fprintf(fp, "\r\n====== Exit ======\r\n");
        fclose(fp);
    }

    printf("[+] All Right!\r\n");
}
Esempio n. 18
0
void
tds_connection_close(TDSCONNECTION *conn)
{
	unsigned n = 0;

	if (!TDS_IS_SOCKET_INVALID(conn->s)) {
		/* TODO check error ?? how to return it ?? */
		CLOSESOCKET(conn->s);
		conn->s = INVALID_SOCKET;
	}

	tds_mutex_lock(&conn->list_mtx);
	for (; n < conn->num_sessions; ++n)
		if (TDSSOCKET_VALID(conn->sessions[n]))
			tds_set_state(conn->sessions[n], TDS_DEAD);
	tds_mutex_unlock(&conn->list_mtx);
}
Esempio n. 19
0
/*
====================
 initialize server socket
====================
*/
SOCKET initServerSock (int port, int backLog)
{
    struct sockaddr_in sa;
    SOCKET sock;
    sock = socket (PF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        outLog ((char*)"InitServerSock(), socket (..) failed [PORT: %d].. \r\n", port);
        return (-1);
    }
    int opt = 1;

    if (setsockopt (sock, SOL_SOCKET, SO_REUSEADDR, \
                   (char*) &opt, sizeof (opt)) < 0) {
        outLog ((char*)"* Error: setsockopt REUSEADDR\r\n");
        exit (1);
    }

    struct linger ld;
    ld.l_onoff = 0;
    ld.l_linger = 0;
    if (setsockopt (sock, SOL_SOCKET, SO_LINGER, \
                   (char*) &ld, sizeof (ld)) < 0)
        outLog ((char*)"* Error: setsockopt SO_LINGER ...\r\n");

    (void) memset ((char*)&sa, 0x00, sizeof (sa));
    sa.sin_family = PF_INET;
    sa.sin_port = htons (port);
    sa.sin_addr.s_addr = INADDR_ANY;

    if (bind (sock, (struct sockaddr*)&sa, sizeof (sa)) < 0)
    {
        outLog ((char*)"InitServerSock(), bind (..) failed [PORT: %d].. \r\n", port);
        CLOSESOCKET (sock);
        return (-1);
    }

    setNonblock (sock);

    listen (sock, backLog);

    return (sock);
}
Esempio n. 20
0
static int stream_writeL(lua_State *L) {
	struct stream *stream;
	const char *header;
	ssize_t n;
	size_t len;

	/*
	 * 1: Stream (self)
	 * 2: Playback (self)
	 * 3: header
	 */

	stream = lua_touserdata(L, 1);
	header = lua_tolstring(L, 3, &len);

	while (len > 0) {
		n = send(stream->fd, header, len, 0);

		if (n < 0) {
			CLOSESOCKET(stream->fd);

			lua_pushnil(L);
			lua_pushstring(L, strerror(SOCKETERROR));
			return 2;
		}

		len -= n;
	}

	/*
	if (shutdown(stream->fd, SHUT_WR) != 0) {
		CLOSESOCKET(stream->fd);

		lua_pushnil(L);
		lua_pushstring(L, strerror(SOCKETERROR));
		return 2;
	}
	*/

	lua_pushboolean(L, TRUE);
	return 1;
}
Esempio n. 21
0
int makeClientSocket(const char *hostname, int port){
    int sock;
    struct hostent *host;
    struct sockaddr_in addr;
    if((host = gethostbyname(hostname)) == NULL ){
        perror(hostname);
        abort();
    }
    sock = socket(PF_INET, SOCK_STREAM, 0);
    memset(&addr, 0, sizeof(addr));
    addr.sin_family         = AF_INET;
    addr.sin_port           = htons(port);
    addr.sin_addr.s_addr    = *(long*)(host->h_addr);
    if(connect(sock, (struct sockaddr*)&addr, sizeof(addr)) != 0){
        CLOSESOCKET(sock);
        perror(hostname);
        abort();
    }
    return sock;
}
Esempio n. 22
0
static int stream_disconnectL(lua_State *L) {
	struct stream *stream;

	/*
	 * 1: self
	 */

	stream = lua_touserdata(L, 1);

	if (stream->body) {
		free(stream->body);
		stream->body = NULL;
		stream->body_len = 0;
	}

	if (stream->fd) {
		CLOSESOCKET(stream->fd);
		stream->fd = 0;
	}

	return 0;
}
Esempio n. 23
0
static size_t
ServerNetworkLayerTCP_stop(ServerNetworkLayerTCP *layer, UA_Job **jobs) {
    UA_LOG_INFO(layer->layer.logger, UA_LOGCATEGORY_NETWORK,
                "Shutting down the TCP network layer with %d open connection(s)", layer->mappingsSize);
    shutdown(layer->serversockfd,2);
    CLOSESOCKET(layer->serversockfd);
    UA_Job *items = malloc(sizeof(UA_Job) * layer->mappingsSize * 2);
    if(!items)
        return 0;
    for(size_t i = 0; i < layer->mappingsSize; i++) {
        socket_close(layer->mappings[i].connection);
        items[i*2].type = UA_JOBTYPE_DETACHCONNECTION;
        items[i*2].job.closeConnection = layer->mappings[i].connection;
        items[(i*2)+1].type = UA_JOBTYPE_METHODCALL_DELAYED;
        items[(i*2)+1].job.methodCall.method = FreeConnectionCallback;
        items[(i*2)+1].job.methodCall.data = layer->mappings[i].connection;
    }
#ifdef _WIN32
    WSACleanup();
#endif
    *jobs = items;
    return layer->mappingsSize*2;
}
Esempio n. 24
0
void slimaudio_http_disconnect(slimaudio_t *audio) {
	pthread_mutex_lock(&audio->http_mutex);

	if (audio->http_state == STREAM_PLAYING)
	{
		DEBUGF("slimaudio_http_disconnect: state=%i\n", audio->http_state);

		audio->http_state = STREAM_STOP;

		/* closing socket and buffer will wake the http thread */
		CLOSESOCKET(audio->streamfd);
		slimaudio_buffer_close(audio->decoder_buffer);

		pthread_cond_broadcast(&audio->http_cond);

		while (audio->http_state == STREAM_STOP)
		{
			pthread_cond_wait(&audio->http_cond, &audio->http_mutex);
		}
	}

	pthread_mutex_unlock(&audio->http_mutex);
}
Esempio n. 25
0
static void
socket_close(UA_Connection *connection) {
    connection->state = UA_CONNECTION_CLOSED;
    shutdown(connection->sockfd,2);
    CLOSESOCKET(connection->sockfd);
}
Esempio n. 26
0
static UA_StatusCode
ServerNetworkLayerTCP_start(UA_ServerNetworkLayer *nl) {
    ServerNetworkLayerTCP *layer = nl->handle;
#ifdef _WIN32
    if((layer->serversockfd = socket(PF_INET, SOCK_STREAM,0)) == (UA_Int32)INVALID_SOCKET) {
        UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Error opening socket, code: %d",
                       WSAGetLastError());
        return UA_STATUSCODE_BADINTERNALERROR;
    }
#else
    if((layer->serversockfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
        UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Error opening socket");
        return UA_STATUSCODE_BADINTERNALERROR;
    }
#endif
    const struct sockaddr_in serv_addr =
        {.sin_family = AF_INET, .sin_addr.s_addr = INADDR_ANY,
         .sin_port = htons(layer->port), .sin_zero = {0}};
    int optval = 1;
    if(setsockopt(layer->serversockfd, SOL_SOCKET,
                  SO_REUSEADDR, (const char *)&optval, sizeof(optval)) == -1) {
        UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK,
                       "Error during setting of socket options");
        CLOSESOCKET(layer->serversockfd);
        return UA_STATUSCODE_BADINTERNALERROR;
    }
    if(bind(layer->serversockfd, (const struct sockaddr *)&serv_addr,
            sizeof(serv_addr)) < 0) {
        UA_LOG_WARNING(layer->logger, UA_LOGCATEGORY_NETWORK, "Error during socket binding");
        CLOSESOCKET(layer->serversockfd);
        return UA_STATUSCODE_BADINTERNALERROR;
    }
    socket_set_nonblocking(layer->serversockfd);
    listen(layer->serversockfd, MAXBACKLOG);
    UA_LOG_INFO(layer->logger, UA_LOGCATEGORY_NETWORK, "TCP network layer listening on %.*s",
                nl->discoveryUrl.length, nl->discoveryUrl.data);
    return UA_STATUSCODE_GOOD;
}

static size_t
ServerNetworkLayerTCP_getJobs(UA_ServerNetworkLayer *nl, UA_Job **jobs, UA_UInt16 timeout) {
    ServerNetworkLayerTCP *layer = nl->handle;
    fd_set fdset;
    UA_Int32 highestfd = setFDSet(layer, &fdset);
    struct timeval tmptv = {0, timeout};
    UA_Int32 resultsize;
    resultsize = select(highestfd+1, &fdset, NULL, NULL, &tmptv);
    if(resultsize < 0) {
        *jobs = NULL;
        return 0;
    }

    /* accept new connections (can only be a single one) */
    if(FD_ISSET(layer->serversockfd, &fdset)) {
        resultsize--;
        struct sockaddr_in cli_addr;
        socklen_t cli_len = sizeof(cli_addr);
        int newsockfd = accept(layer->serversockfd, (struct sockaddr *) &cli_addr, &cli_len);
        int i = 1;
        setsockopt(newsockfd, IPPROTO_TCP, TCP_NODELAY, (void *)&i, sizeof(i));
        if(newsockfd >= 0) {
            socket_set_nonblocking(newsockfd);
            ServerNetworkLayerTCP_add(layer, newsockfd);
        }
    }

    /* alloc enough space for a cleanup-connection and free-connection job per resulted socket */
    if(resultsize == 0)
        return 0;
    UA_Job *js = malloc(sizeof(UA_Job) * resultsize * 2);
    if(!js)
        return 0;

    /* read from established sockets */
    size_t j = 0;
    UA_ByteString buf = UA_BYTESTRING_NULL;
    for(size_t i = 0; i < layer->mappingsSize && j < (size_t)resultsize; i++) {
        if(!(FD_ISSET(layer->mappings[i].sockfd, &fdset)))
            continue;
        UA_StatusCode retval = socket_recv(layer->mappings[i].connection, &buf, 0);
        if(retval == UA_STATUSCODE_GOOD) {
            UA_Boolean realloced = UA_FALSE;
            retval = UA_Connection_completeMessages(layer->mappings[i].connection, &buf, &realloced);
            if(retval != UA_STATUSCODE_GOOD || buf.length == 0)
                continue;
            js[j].job.binaryMessage.connection = layer->mappings[i].connection;
            js[j].job.binaryMessage.message = buf;
            if(!realloced)
                js[j].type = UA_JOBTYPE_BINARYMESSAGE_NETWORKLAYER;
            else
                js[j].type = UA_JOBTYPE_BINARYMESSAGE_ALLOCATED;
            j++;
        } else if (retval == UA_STATUSCODE_BADCONNECTIONCLOSED) {
            UA_Connection *c = layer->mappings[i].connection;
            /* the socket was closed from remote */
            js[j].type = UA_JOBTYPE_DETACHCONNECTION;
            js[j].job.closeConnection = layer->mappings[i].connection;
            layer->mappings[i] = layer->mappings[layer->mappingsSize-1];
            layer->mappingsSize--;
            j++;
            js[j].type = UA_JOBTYPE_METHODCALL_DELAYED;
            js[j].job.methodCall.method = FreeConnectionCallback;
            js[j].job.methodCall.data = c;
            j++;
        }
    }

    if(j == 0) {
    	free(js);
    	js = NULL;
    }

    *jobs = js;
    return j;
}
Esempio n. 27
0
BOOL CClient::Connect(const std::string& server_ip, unsigned int server_port)
{
    AUTO_LOG_FUNCTION;
    if (m_bConnectionEstablished)
        return TRUE;
    do {
        struct sockaddr_in server_addr;
        memset(&server_addr, 0, sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_addr.S_un.S_addr = inet_addr(server_ip.c_str());
        server_addr.sin_port = htons(static_cast<u_short>(server_port));

        if ((m_socket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
            JLOG(_T("socket failed\n"));
            JLOG(FormatWSAError(WSAGetLastError()));
            break;
        }

        // set the socket in non-blocking mode.
        unsigned long non_blocking_mode = 1;
        int result = ioctlsocket(m_socket, FIONBIO, &non_blocking_mode);
        if (result != NO_ERROR) {
            JLOG(_T("ioctlsocket failed : %d\n"), result);
            JLOG(FormatWSAError(WSAGetLastError()));
            CLOSESOCKET(m_socket);
            break;
        }

        int ret = connect(m_socket, (struct sockaddr *) &server_addr,
                          sizeof(struct sockaddr));

        if (ret != -1) {
            JLOGA("connect to %s:%d failed\n", server_ip.c_str(), server_port);
            JLOG(FormatWSAError(WSAGetLastError()));
            CLOSESOCKET(m_socket);
            break;
        }

        TIMEVAL tm;
        tm.tv_sec = 3;
        tm.tv_usec = 0;
        fd_set fdset;
        FD_ZERO(&fdset);
        FD_SET(m_socket, &fdset);
        if (select(m_socket + 1, nullptr, &fdset, nullptr, &tm) <= 0) {
            CLOSESOCKET(m_socket);
            break;
        }

        int error, len;
        len = sizeof(int);
        getsockopt(m_socket, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
        if (error != NO_ERROR) {
            JLOGA("connect to %s:%d failed\n", server_ip.c_str(), server_port);
            JLOG(FormatWSAError(WSAGetLastError()));
            CLOSESOCKET(m_socket);
            break;
        }

        // set the socket in blocking mode.
        non_blocking_mode = 0;
        result = ioctlsocket(m_socket, FIONBIO, &non_blocking_mode);
        if (result != NO_ERROR) {
            JLOG(_T("ioctlsocket failed : %d\n"), result);
            JLOG(FormatWSAError(WSAGetLastError()));
            CLOSESOCKET(m_socket);
            break;
        }


        m_bConnectionEstablished = TRUE;
        m_buff.Clear();
        last_recv_time_ = COleDateTime::GetTickCount();
        last_send_link_test_time_ = COleDateTime::GetTickCount();

        return TRUE;
    } while (0);


    return FALSE;
}
Esempio n. 28
0
int callapi(char *command, char *host, short int port)
{
	char buf[RECVSIZE+1];
	struct hostent *ip;
	struct sockaddr_in serv;
	SOCKETTYPE sock;
	int ret = 0;
	int n, p;

	SOCKETINIT;

	ip = gethostbyname(host);

	sock = socket(AF_INET, SOCK_STREAM, 0);
	if (sock == INVSOCK) {
		printf("Socket initialisation failed: %s\n", SOCKERRMSG);
		return 1;
	}

	memset(&serv, 0, sizeof(serv));
	serv.sin_family = AF_INET;
	serv.sin_addr = *((struct in_addr *)ip->h_addr);
	serv.sin_port = htons(port);

	if (SOCKETFAIL(connect(sock, (struct sockaddr *)&serv, sizeof(struct sockaddr)))) {
		printf("Socket connect failed: %s\n", SOCKERRMSG);
		return 1;
	}

	n = send(sock, command, strlen(command), 0);
	if (SOCKETFAIL(n)) {
		printf("Send failed: %s\n", SOCKERRMSG);
		ret = 1;
	}
	else {
		p = 0;
		buf[0] = '\0';
		while (p < RECVSIZE) {
			n = recv(sock, &buf[p], RECVSIZE - p , 0);

			if (SOCKETFAIL(n)) {
				printf("Recv failed: %s\n", SOCKERRMSG);
				ret = 1;
				break;
			}

			if (n == 0)
				break;

			p += n;
			buf[p] = '\0';
		}

		if (ONLY)
			printf("%s\n", buf);
		else {
			printf("Reply was '%s'\n", buf);
			display(buf);
		}
	}

	CLOSESOCKET(sock);

	return ret;
}
Esempio n. 29
0
File: HTran.cpp Progetto: bGN4/HTran
/*************************************************************************************
*                                                                                    *
* ConnectHost:ConnectPort transmit to TransmitHost:TransmitPort                      *
*                                                                                    *
*************************************************************************************/
void conn2conn(char *host1, int port1, char *host2, int port2) {
    HANDLE hThread = NULL;
    SOCKET sockfd1, sockfd2;
    struct transocket sock;
    DWORD  dwThreadID;
    fd_set fds;
    long   l;
    char   buffer[MAXSIZE];

    while (1) {
        while (connectnum) {
            if (connectnum < CONNECTNUM) {
                SLEEP(1000);
                break;
            } else {
                SLEEP(TIMEOUT * 1000);
                continue;
            }
        }

        if ((sockfd1 = create_socket()) == 0) return;
        if ((sockfd2 = create_socket()) == 0) return;

        printf("[+] Make a Connection to %s:%d....\r\n", host1, port1);
        fflush(stdout);
        if (client_connect(sockfd1, host1, port1) == 0) {
            CLOSESOCKET(sockfd1);
            CLOSESOCKET(sockfd2);
            SLEEP(3000);
            continue;
        }

        // fix by bkbll
        // if host1:port1 recved data, than connect to host2,port2
        l = 0;
        memset(buffer, 0, MAXSIZE);
        while (1) {
            FD_ZERO(&fds);
            FD_SET(sockfd1, &fds);
            if (select(sockfd1 + 1, &fds, NULL, NULL, NULL) == SOCKET_ERROR) {
                if (errno == WSAEINTR) {
                    continue;
                }
                break;
            }
            if (FD_ISSET(sockfd1, &fds)) {
                l = recv(sockfd1, buffer, MAXSIZE, 0);
                break;
            }
            SLEEP(5);
        }
        if (l <= 0) {
            printf("[-] There is a error...Create a new connection.\r\n");
            continue;
        }
        printf("[+] Connect OK!\r\n");
        while (1) {
            printf("[+] Make a Connection to %s:%d....\r\n", host2, port2);
            fflush(stdout);
            if (client_connect(sockfd2, host2, port2) == 0) {
                CLOSESOCKET(sockfd1);
                CLOSESOCKET(sockfd2);
                SLEEP(3000);
                continue;
            }

            if (send(sockfd2, buffer, l, 0) == SOCKET_ERROR) {
                printf("[-] Send failed.\r\n");
                continue;
            }

            l = 0;
            memset(buffer, 0, MAXSIZE);
            break;
        }

        printf("[+] All Connect OK!\r\n");

        sock.fd1 = sockfd1;
        sock.fd2 = sockfd2;

#ifdef WIN32
        if (NULL == (hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)transmitdata, (LPVOID)&sock, 0, &dwThreadID))) {
            TerminateThread(hThread, 0);
            return;
        }
#else
        if (pthread_create((pthread_t*)&hThread, NULL, &transmitdata, (void *)&sock)) {
            pthread_cancel((pthread_t)hThread);
            return;
        }
#endif //WIN32

        ++connectnum;
        SLEEP(1000);
        printf("[+] CreateThread OK!\r\n");
    }
}
Esempio n. 30
0
File: HTran.cpp Progetto: bGN4/HTran
/*************************************************************************************
*                                                                                    *
* LocalHost:ConnectPort transmit to TransmitHost:TransmitPort                        *
*                                                                                    *
*************************************************************************************/
void bind2conn(int port1, char *host, int port2) {
    SOCKET sockfd, sockfd1, sockfd2;
    struct sockaddr_in remote;
    struct transocket sock;

    socklen_t size;
    DWORD dwThreadID;
    HANDLE hThread = NULL;

    char buffer[1024];

    if (port1 > 65535 || port1 < 1) {
        printf("[-] ConnectPort invalid.\r\n");
        return;
    }

    if (port2 > 65535 || port2 < 1) {
        printf("[-] TransmitPort invalid.\r\n");
        return;
    }

    memset(buffer, 0, 1024);

    if ((sockfd = create_socket()) == INVALID_SOCKET) return;

    if (create_server(sockfd, port1) == 0) {
        CLOSESOCKET(sockfd);
        return;
    }

    size = sizeof(struct sockaddr);
    while (1) {
        printf("[+] Waiting for Client ......\r\n");
        if ((sockfd1 = accept(sockfd, (struct sockaddr *)&remote, &size)) < 0) {
            printf("[-] Accept error.\r\n");
            continue;
        }

        printf("[+] Accept a Client from %s:%d ......\r\n",
            inet_ntoa(remote.sin_addr), ntohs(remote.sin_port));
        if ((sockfd2 = create_socket()) == 0) {
            CLOSESOCKET(sockfd1);
            continue;
        }
        printf("[+] Make a Connection to %s:%d ......\r\n", host, port2);
        fflush(stdout);

        if (client_connect(sockfd2, host, port2) == 0) {
            CLOSESOCKET(sockfd2);
            sprintf(buffer, "[SERVER]connection to %s:%d error\r\n", host, port2);
            send(sockfd1, buffer, strlen(buffer), 0);
            memset(buffer, 0, 1024);
            CLOSESOCKET(sockfd1);
            continue;
        }

        printf("[+] Connect OK!\r\n");

        sock.fd1 = sockfd1;
        sock.fd2 = sockfd2;

#ifdef WIN32
        if (NULL == (hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)transmitdata, (LPVOID)&sock, 0, &dwThreadID))) {
            TerminateThread(hThread, 0);
            return;
        }
#else
        if (pthread_create((pthread_t*)&hThread, NULL, &transmitdata, (void *)&sock)) {
            pthread_cancel((pthread_t)hThread);
            return;
        }
#endif //WIN32

        SLEEP(1000);
        printf("[+] CreateThread OK!\r\n\n");
    }
}