Exemple #1
0
void *events_clientize(void *param) {
	logprintf(LOG_STACK, "%s(...)", __FUNCTION__);

	unsigned int failures = 0;
	while(loop && failures <= 5) {
		struct ssdp_list_t *ssdp_list = NULL;
		int standalone = 0;
		settings_find_number("standalone", &standalone);
		if(ssdp_seek(&ssdp_list) == -1 || standalone == 1) {
			logprintf(LOG_DEBUG, "no pilight ssdp connections found");
			char server[16] = "127.0.0.1";
			if((sockfd = socket_connect(server, (unsigned short)socket_get_port())) == -1) {
				logprintf(LOG_DEBUG, "could not connect to pilight-daemon");
				failures++;
				continue;
			}
		} else {
			if((sockfd = socket_connect(ssdp_list->ip, ssdp_list->port)) == -1) {
				logprintf(LOG_DEBUG, "could not connect to pilight-daemon");
				failures++;
				continue;
			}
		}
		if(ssdp_list) {
			ssdp_free(ssdp_list);
		}

		struct JsonNode *jclient = json_mkobject();
		struct JsonNode *joptions = json_mkobject();
		json_append_member(jclient, "action", json_mkstring("identify"));
		json_append_member(joptions, "config", json_mknumber(1, 0));
		json_append_member(jclient, "options", joptions);
		json_append_member(jclient, "media", json_mkstring("all"));
		char *out = json_stringify(jclient, NULL);
		socket_write(sockfd, out);
		json_free(out);
		json_delete(jclient);

		if(socket_read(sockfd, &recvBuff, 0) != 0
			 || strcmp(recvBuff, "{\"status\":\"success\"}") != 0) {
				failures++;
			continue;
		}
		failures = 0;
		while(loop) {
			if(socket_read(sockfd, &recvBuff, 0) != 0) {
				break;
			} else {
				events_queue(recvBuff);
			}
		}
	}

	if(recvBuff) {
		FREE(recvBuff);
		recvBuff = NULL;
	}
	socket_close(sockfd);
	return 0;
}
Exemple #2
0
int socket_setup(void)
{

    s8 rc = SOC_SUCCESS;

    if (setting.addr_type == ADDR_TYPE_IP)
    {
        return socket_connect(setting.ipaddr);
    }
    else
    {
        u8 ipaddr[4] = {0};
        u8 len = 0;

        eat_soc_gethost_notify_register(hostname_notify_cb);
        rc = eat_soc_gethostbyname(setting.domain, ipaddr, &len, request_id++);
        if (rc == SOC_WOULDBLOCK)
        {
            LOG_DEBUG("eat_soc_gethostbyname wait callback.");
            return ERR_WAITING_HOSTNAME2IP;
        }
        else if (rc == SOC_SUCCESS)
        {
            LOG_DEBUG("host:%s -> %d.%d.%d.%d:%d.", setting.domain, ipaddr[0], ipaddr[1], ipaddr[2], ipaddr[3], setting.port);
            return socket_connect(ipaddr);
        }
        else
        {
            LOG_ERROR("eat_soc_gethostbyname error!");
            return ERR_GET_HOSTBYNAME_FAILED;
        }
    }
}
Exemple #3
0
int proxy_connect(struct proxy *self, const char *dst_ip, unsigned short dst_port)
{
	int err;

	err = socket_connect(self->s, self->ip, self->port);
	if (err < 0)
		return err;

	struct socket5_select_request	request;
	struct socket5_select_response	response;

	assert(self->ip);
	assert(self->usr);
	assert(self->pwd);

	err = socket_connect(self->s, self->ip, self->port);
	if (err < 0)
		return err;

	request.ver = 0x05;
	request.method_nr = 2;
	request.method_tbl[0] = 0x00;	/* no auth */
	request.method_tbl[2] = 0x02;	/* user pwd */

	err = socket_send_data(
				self->s,
				(char *)&request,
				2 + request.method_nr * sizeof(request.method_tbl[0])
				);

	if (err < 0)
		return err;

	err = socket_recv_data(
				self->s,
				(char *)&response,
				sizeof(response)
				);

	if (err < 0)
		return err;

	if (response.method == 0x02)
		err = auth(self->s, self->usr, self->pwd);

	if (err < 0)
		return err;

	err = conn(self->s, dst_ip, dst_port);
	
	return err;
}
Exemple #4
0
int
connection_client_connect(struct connection *c,
                          const struct sockaddr *server_address,
                          size_t server_address_length,
                          uint32_t seed)
{
    int ret;
    struct timeval tv;

    assert(c->client.client == NULL);

    int fd;

    const struct addrinfo *socks4_address =
        c->instance->config->socks4_address;
    if (socks4_address != NULL) {
        fd = socket_connect(socks4_address->ai_family, SOCK_STREAM, 0,
                            socks4_address->ai_addr, socks4_address->ai_addrlen);
        if (fd < 0)
            return -fd;

        if (!socks_connect(fd, server_address))
            return -1;
    } else {
        fd = socket_connect(server_address->sa_family, SOCK_STREAM, 0,
                            server_address, server_address_length);
        if (fd < 0)
            return -fd;
    }

    ret = uo_client_create(fd, seed,
                           c->client_version.seed,
                           &client_handler, c,
                           &c->client.client);
    if (ret != 0) {
        close(fd);
        return ret;
    }

    if (client_version_defined(&c->client_version))
        uo_client_set_protocol(c->client.client,
                               c->client_version.protocol);

    tv.tv_sec = 30;
    tv.tv_usec = 0;
    evtimer_set(&c->client.ping_event, connection_ping_event_callback,
                &c->client);
    evtimer_add(&c->client.ping_event, &tv);

    return 0;
}
Exemple #5
0
bool
bot_init_connection(struct bot *bot)
{
	DEBUG(LOG_VERBOSE, "bot init connection\n");
	
	return socket_connect(bot->socket);
}
Exemple #6
0
static void run_networking_test(bool server)
{
    if (!server) {
        connection_t *conn = connection_create(&on_connect);
        if (!conn)
            return;

        printf("connecting to localhost on port 1337\n");
        socket_connect(conn, "127.0.0.1", "1337");

        char buffer[1024];
        while (fgets(buffer, sizeof buffer, stdin))
            socket_write(conn, buffer);
    } else {
        socket_t *sock = socket_create(on_accept);
        if (!sock)
            return;

        printf("Server will bind to port 1337.\n");
        socket_listen(sock, NULL, 1337, 10);
        while (1) {
            sleep(5);
            printf("%d connections ATM\n", sock->num_connections);
        }
    }
}
Exemple #7
0
    int main(int argc, char **argv) {

        initiate(argc, argv); /* initialize executor */
        #ifndef BASIC
        socket_setup();
        network_socket = socket_connect();
        #endif
        runsys(); /* initialize running system */
        if (has_network_socket()) {
            request_id();
            GraphRes = get_graph_res();
            graph_setstatus();
            if (GraphRes < 0) exit(12);
            if (remote) send_ready();
        }

        setjmp (contenv); /* set label for continue long jump */
        while (TRUE) { /* repeat until exit() is called */
            get_internal();
            schedule(); /* reschedule current process */
            if (ready != 0) {
                decode(); /* fetch instruction */
                execute(); /* and execute it */
            }
        }
        return 0;
    } /* end main */
Exemple #8
0
void *__server(void *ptr)
{
	t_context *C=ctx_get();
	char msg[30];

	if(!server_init)
	{
		socket_connect(C->server->socket,9901);
		server_init=1;
		sprintf(msg,"listening on port %d",C->server->socket->portno);
		term_print(C->term,msg);

		if(C->app->off_screen)
		{
			printf("listening on port %d\n",C->server->socket->portno);
		}
	}
	else
	{
		socket_listen(C->server->socket);
		if(C->app->off_screen)
		{
			printf("waiting for connection");
		}

	}
	return NULL;
}
Exemple #9
0
int nettest2(void)
{
	int err;
	sockaddr addr;

	fd = socket_create(SOCK_PROTO_TCP, 0);
	printf("created socket, fd %d\n", fd);
	if(fd < 0)
		return 0;

	memset(&addr, 0, sizeof(addr));
	addr.addr.len = 4;
	addr.addr.type = ADDR_TYPE_IP;
	addr.port = 9;
	NETADDR_TO_IPV4(addr.addr) = IPV4_DOTADDR_TO_ADDR(63,203,215,73);

	err = socket_connect(fd, &addr);
	printf("socket_connect returns %d\n", err);
	if(err < 0)
		return err;

	for(;;) {
		char buf[4096];
		socket_write(fd, buf, sizeof(buf));
	}
	return 0;
}
Exemple #10
0
int nettest1(void)
{
	int err;
	sockaddr addr;

	fd = socket_create(SOCK_PROTO_TCP, 0);
	printf("created socket, fd %d\n", fd);
	if(fd < 0)
		return 0;

	memset(&addr, 0, sizeof(addr));
	addr.addr.len = 4;
	addr.addr.type = ADDR_TYPE_IP;
//	addr.port = 19;
//	NETADDR_TO_IPV4(addr.addr) = IPV4_DOTADDR_TO_ADDR(63,203,215,73);
//	addr.port = 23;
//	NETADDR_TO_IPV4(addr.addr) = IPV4_DOTADDR_TO_ADDR(192,168,0,3);
	addr.port = 6667;
	NETADDR_TO_IPV4(addr.addr) = IPV4_DOTADDR_TO_ADDR(209,131,227,242);

	err = socket_connect(fd, &addr);
	printf("socket_connect returns %d\n", err);
	if(err < 0)
		return err;

	exit_sem = _kern_sem_create(0, "exit");

	_kern_thread_resume_thread(_kern_thread_create_thread("read_thread", &read_thread, NULL));
	_kern_thread_resume_thread(_kern_thread_create_thread("write_thread", &write_thread, NULL));

	for(;;)
		_kern_sem_acquire(exit_sem, 1);

	return 0;
}
Exemple #11
0
int nettest4(void)
{
	int err;
	sockaddr addr;

	fd = socket_create(SOCK_PROTO_TCP, 0);
	printf("created socket, fd %d\n", fd);
	if(fd < 0)
		return 0;

	memset(&addr, 0, sizeof(addr));
	addr.addr.len = 4;
	addr.addr.type = ADDR_TYPE_IP;
	addr.port = 1900;
	NETADDR_TO_IPV4(addr.addr) = IPV4_DOTADDR_TO_ADDR(63,203,215,73);

	err = socket_connect(fd, &addr);
	printf("socket_connect returns %d\n", err);
	if(err < 0)
		return err;

	usleep(5000000);

	err = socket_close(fd);
	printf("socket_close returns %d\n", err);

	return 0;
}
Exemple #12
0
Display *OpenDisplay(char *hostname, int port)
{
    Display *display = NULL;
    Socket *socket = NULL;
    char *port_buf = NULL;

    port_buf = int_to_string(port);
    if (port_buf == NULL)
        return NULL;

    socket = socket_new(Socket_Blocking);
    if (socket_connect(socket, hostname, port_buf) != 0) {
        socket_free(socket);
        free(port_buf);
        return NULL;
    }

    free(port_buf);

    display = (Display *) malloc(sizeof(Display));
    
    display->socket = socket;
    display->hostname = strdup(hostname);
    display->port = port;
    display->callbacks = callbacks_new();
    
    return display;
}
Exemple #13
0
// main
//-----------------------------------------------------------------------------------
int
main (int argc, char *argv[])
{
  int s, size;
  pthread_t thread;
  char buf[256];

  if (argc == 1)
    {
      printf ("usage: client <server IP address>\n");
      exit (1);
    }

  s = socket_connect (argv[1], 1024);

  pthread_mutex_init (&g_mutex, NULL);
  pthread_create (&thread, NULL, thread_recv, (void *) &s);

  // メインループ
  //---------------------------------------------------
  while (g_main_loop)
    {
      fgets (buf, 256, stdin);
      size = strlen (buf);
      fprintf (stderr, "sending[%d] %s", size, buf);
      socket_write (s, &size, sizeof (int));
      socket_write (s, buf, size);
    }

  pthread_join (thread, NULL);

  exit (0);
}
Exemple #14
0
/**
* 作用: 连接到一个FTP服务器,返回socket
* 参数: IP或域名, 端口
* 返回值: Socket套接字
* */
SOCKET connect_server(char *host, int port)
{
	SOCKET ctrl_sock;
	char buf[BUFSIZ];
	int result;
	ssize_t len;
	memset(buf, 0, sizeof(buf));

	ctrl_sock = socket_connect(host, port);
	if (-1 == ctrl_sock)
	{
		return -1;
	}
	while ((len = recv(ctrl_sock, buf, BUFSIZ, 0)) > 0)
	{
		buf[len] = 0;
		printf("buf\n");
	}
	sscanf(buf, "%d", &result);

	if (FTP_SERVICE_READY != result)
	{
		logger.error("FTP not ready, close the socket!");
		closesocket(ctrl_sock); // 关闭socket
		return -1;
	}
	return ctrl_sock;
}
Exemple #15
0
/**
* 作用: 连接到PASV接口
*       PASV(被动)方式的连接过程是:
*       客户端向服务器的FTP端口(默认是21)发送连接请求,
*       服务器接受连接,建立一条命令链路。
* 参数: 命令链路SOCKET cmd-socket
* 返回值: 数据链路SOCKET raw-socket  -1 表示创建失败
* */
SOCKET ftp_pasv_connect(SOCKET c_sock)
{
	SOCKET r_sock;
	int send_result;
	ssize_t len;
	int addr[6]; //IP*4+PORT*2
	char buf[BUFSIZ];
	char result_buf[BUFSIZ];
	memset(result_buf, 0, sizeof(result_buf));

	// 设置PASV被动模式
	memset(buf, sizeof(buf), 0);
	sprintf(buf, "PASV\r\n");
	send_result = ftp_sendcmd_re(c_sock, buf, result_buf, &len);
	if (send_result == 0)
	{
		sscanf(result_buf, "%*[^(](%d,%d,%d,%d,%d,%d)", &addr[0], &addr[1], &addr[2], &addr[3], &addr[4], &addr[5]);
	}

	// 连接PASV端口
	memset(buf, sizeof(buf), 0);
	sprintf(buf, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);
	r_sock = socket_connect(buf, addr[4] * 256 + addr[5]);
	if (r_sock == -1)
	{
		return -1;
	}
	return r_sock;
}
// main
//-----------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
    int sock, size, ret;
    char buf[BUFSIZE];

    if (argc == 1) {
	printf("usage: client <server IP address>\n");
	exit(1);
    }

    sock = socket_connect(argv[1], PORT);

    // メインループ
    //---------------------------------------------------
    do {
	/* キー入力 */
	fgets(buf, 256, stdin);
	size = strlen(buf);

	/* Serverへ送信 */
	fprintf(stdout, "sending  :[%d] (%d)%s", sock, size, buf);
	write(sock, buf, size);

	/* Serverから受信 */
	ret = read(sock, buf, BUFSIZE);
	fprintf(stdout, "received :[%d] (%d)%s", sock, ret, buf);
    }
    while (ret > 0);

    socket_close(sock);

    exit(0);
}
static int
connection_init( Connection*  conn )
{
    HttpService*      service = (HttpService*) conn->root->service;
    ProxyConnection*  root    = conn->root;
    stralloc_t*       str     = root->str;

    proxy_connection_rewind(root);
    stralloc_add_format(str, "CONNECT %s HTTP/" HTTP_VERSION "\r\n",
                        sock_address_to_string(&root->address));

    stralloc_add_bytes(str, service->footer, service->footer_len);

    if (!socket_connect( root->socket, &service->server_addr )) {
        /* immediate connection ?? */
        conn->state = STATE_SEND_HEADER;
        PROXY_LOG("%s: immediate connection", root->name);
    }
    else {
        if (errno == EINPROGRESS || errno == EWOULDBLOCK) {
            conn->state = STATE_CONNECTING;
            PROXY_LOG("%s: connecting", root->name);
        }
        else {
            PROXY_LOG("%s: cannot connect to proxy: %s", root->name, errno_str);
            return -1;
        }
    }
    return 0;
}
Exemple #18
0
int SocketConnector::connect( const std::string& address, int port, bool noDelay,
                              int sendBufSize, int rcvBufSize , int mode)
{

  int socket = socket_createConnector(mode);

  if ( socket != -1 )
  {
    if( noDelay )
      socket_setsockopt( socket, TCP_NODELAY );
    if( sendBufSize )
      socket_setsockopt( socket, SO_SNDBUF, sendBufSize );
    if( rcvBufSize )
      socket_setsockopt( socket, SO_RCVBUF, rcvBufSize );

    if( socket_connect( socket, address.c_str(), port ) < 0 )
    {
      DWORD code = GetLastError();
      socket_close( socket );
      SetLastError(code);
      socket = -1;
    }
    else
    {
      m_monitor.addConnect( socket );
    }
  }
  return socket;

  
}
    virtual bool initSocket() {
        if (socket==SOCKET_INVALID) {
            socket = socket_create(AF_INET, SOCK_STREAM, IPPROTO_TCP, 54, 0);

            sockaddr_t socketAddr;
            int testResult = 0;

            // the family is always AF_INET
            socketAddr.sa_family = AF_INET;

            socketAddr.sa_data[0] = 0;
            socketAddr.sa_data[1] = 54;

            // the destination IP address: 8.8.8.8
            socketAddr.sa_data[2] = 127;
            socketAddr.sa_data[3] = 0;
            socketAddr.sa_data[4] = 0;
            socketAddr.sa_data[5] = 1;

            testResult = socket_connect(socket, &socketAddr, sizeof(socketAddr));
            if (testResult) {
                socket_close(socket);
                socket = SOCKET_INVALID;
            }
        }
        return socket!=SOCKET_INVALID;
    }
int http_query(char *command, char *host, char *path, int port, char *additional_header, char *data, char *body) {
	int s;
	int status;
	int response_length;
	char buffer[BUFFER_SIZE];
	char *pc;

	if((s = socket_connect(host, port))){
		
		bzero(buffer,BUFFER_SIZE);
		if(data){
			sprintf(buffer,"%s %.256s HTTP/1.0\nContent-length: %d\n\n", command, path, (int)strlen(data));			
		}else{
			sprintf(buffer,"%s %.256s HTTP/1.0\n\n",command, path);
		}
		write(s, buffer, strlen(buffer));  
		// fprintf(stderr, buffer);
		
		if(data){
			write(s,data,strlen(data));
		}
		
		http_readline(s, buffer);
		sscanf(buffer,"HTTP/1.%*d %03d",(int*)&status);;

		while(http_readline(s, buffer)){
			if(*buffer=='\0'){
				break;
			} else {
				// fprintf(stderr, "line:%s\n", buffer);	
				for (pc=buffer; (*pc!=':' && *pc) ; pc++) 
					*pc=tolower(*pc);
				sscanf(buffer,"content-length: %d",&response_length);
			}
		}
		
		*body=0;
		bzero(body,200000);
		if(response_length>0){
			// fprintf(stderr, "body length:%i\n", response_length);
			read(s,body,response_length);
			// fprintf(stderr, "body:%s\n", body);
		}else{
			bzero(buffer,BUFFER_SIZE);
			while(read(s,buffer,BUFFER_SIZE)){
				// fprintf(stderr,"read-%s\n",buffer);
				strncat(body,buffer,BUFFER_SIZE);
				bzero(buffer,BUFFER_SIZE);
			}
		}

		shutdown(s, SHUT_RDWR); 
		close(s);		
		
		return status;
		
	} else {
		return -10;	
	}
}
Exemple #21
0
bool CLIENT_DESC::Connect(int iPhaseWhenSucceed)
{
    if (iPhaseWhenSucceed != 0)
        m_iPhaseWhenSucceed = iPhaseWhenSucceed;

    if (get_global_time() - m_LastTryToConnectTime < 3)	// 3초
        return false;

    m_LastTryToConnectTime = get_global_time();

    if (m_sock != INVALID_SOCKET)
        return false;

    sys_log(0, "SYSTEM: Trying to connect to %s:%d", m_stHost.c_str(), m_wPort);

    m_sock = socket_connect(m_stHost.c_str(), m_wPort);

    if (m_sock != INVALID_SOCKET)
    {
        sys_log(0, "SYSTEM: connected to server (fd %d, ptr %p)", m_sock, this);
        fdwatch_add_fd(m_lpFdw, m_sock, this, FDW_READ, false);
        fdwatch_add_fd(m_lpFdw, m_sock, this, FDW_WRITE, false);
        SetPhase(m_iPhaseWhenSucceed);
        return true;
    }
    else
    {
        SetPhase(PHASE_CLIENT_CONNECTING);
        return false;
    }
}
Exemple #22
0
int UdmHTTPConnect(UDM_ENV * Conf, UDM_CONN *connp,
                   char *hostname, int port, int timeout)
{
  size_t len;
    
  if (!connp || !hostname || !port)
    return -1;

  connp->port= port;
  connp->timeout= timeout;

  len= strlen(hostname);
  connp->hostname= UdmXrealloc(connp->hostname, len+1);
  udm_snprintf(connp->hostname, len+1, "%s", hostname);

  if (UdmHostLookup(&Conf->Hosts,connp)) /* FIXME: not reentrant */
    return -1;

  if (socket_open(connp))
    return -1;

  if (socket_connect(connp))
    return -1;
                          
  return 0;
}
Exemple #23
0
static int timeout_connect( int fd, const struct sockaddr *serv_addr,
	socklen_t addrlen )
{
	if( socket_connect( fd, serv_addr, addrlen) < 0 ) {
		if( errno != EINPROGRESS ) {
			return -1;
		}
	}
	if( wait_socket( fd, WAIT_WRITE  ) <= 0 ) {
		if( errno == 0 ) {
			errno = ETIMEDOUT;
		}
		return -1;
	}

	/* Completed or failed */
	int optval = 0;
	socklen_t optlen = sizeof(optval);
	/* casting  &optval to char* is required for win32 */
	if( getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&optval, &optlen) == -1 ) {
		return -1;
	}
	if (optval != 0) {
		errno = optval;
		return -1;
	}
	return 0;
}
void init_socket_example_connect(int port, uint8_t *ip)
{
   int i = 0;
   int socket = socket_open(TCP_STREAM);
   struct sock_addr addr;
   addr.port = port;
   addr.ip = 0;
   for(i=0; i<4; i++) {
      addr.ip |= ip[i] << i*8;
   }
//   printf("ip is %x\n", addr.ip);
printf("connecting call\n");
   socket_connect(socket, &addr);
printf("connected.\n");
#if 0
   socket_bind(socket, &addr);
   socket_listen(socket, 5);
   struct sock_addr client;
//   printf("Waiting for accept\n");
   logger(SOCKET, NORMAL, "waiting on accept\n");
   pthread_attr_t attr;
   int thread_id = 0;
   while(1) {
      int *socket_child = malloc(sizeof(int));
      *socket_child = socket_accept(socket, &client);
      pthread_create(&thread_id, NULL, DoWork, socket_child); 
   }
#endif
//   printf("accepted the connection\n");
}
Exemple #25
0
int main(int argc, char* argv[]) {
    signal(SIGINT, ftpclient_quit);
    signal(SIGTERM, ftpclient_quit);

    conn_socket = -1;

    int port = 21;
    char* host = "127.0.0.1";

    if (argc != 2 && argc != 3) {
        printf("Usage: %s [host[port]], default host=127.0.0.1 port=21\n", argv[0]);
    } else if (argc == 2) {
        host = argv[1];
    } else if (argc == 3) {
        host = argv[1];
        port = atoi(argv[2]);
    }

    if ((conn_socket = socket_connect(host, port)) < 0)
        die(ERR_SOCKET_CONNECT);

    ftpclient_process(conn_socket);

    return 0;
}
int unix_connect_opts(QemuOpts *opts)
{
    SockAddress  un;
    const char *path = qemu_opt_get(opts, "path");
    int ret, sock;

    sock = socket_create_unix(SOCKET_STREAM);
    if (sock < 0) {
        perror("socket(unix)");
        return -1;
    }

    sock_address_init_unix(&un, path);
    ret = socket_connect(sock, &un);
    sock_address_done(&un);
    if (ret < 0) {
        fprintf(stderr, "connect(unix:%s): %s\n", path, errno_str);
        return -1;
    }


    if (sockets_debug)
        fprintf(stderr, "connect(unix:%s): OK\n", path);
    return sock;
}
Exemple #27
0
static int test_client(struct harness_t *harness_p)
{
    struct ssl_context_t context;
    struct ssl_socket_t ssl_socket;
    struct socket_t socket;
    struct inet_addr_t addr;
    char buf[8];

    /* Create a context with default settings. */
    BTASSERT(ssl_context_init(&context) == 0);

    /* Create a socket and connect to the server. */
    BTASSERT(socket_open_tcp(&socket) == 0);

    inet_aton("1.2.3.4", &addr.ip);
    addr.port = 1234;
    BTASSERT(socket_connect(&socket, &addr) == 0);

    /* Wrap the socket in SSL. */
    BTASSERT(ssl_socket_init(&ssl_socket,
                             &context,
                             &socket,
                             ssl_socket_mode_client_t) == 0);
    BTASSERT(ssl_socket_handshake(&ssl_socket) == 0);

    /* Transfer data to and from the server. */
    BTASSERT(ssl_socket_write(&ssl_socket, "hello", 6) == 6);
    BTASSERT(ssl_socket_read(&ssl_socket, &buf[0], 8) == 8);
    BTASSERT(strcmp("goodbye", buf) == 0);

    /* Close the connection. */
    BTASSERT(socket_close(&socket) == 0);

    return (0);
}
AsyncStatus
asyncConnector_init(AsyncConnector*    ac,
                    const SockAddress* address,
                    LoopIo*            io)
{
    int ret;
    ac->error = 0;
    ac->io    = io;
    ret = socket_connect(io->fd, address);
    if (ret == 0) {
        ac->state = CONNECT_COMPLETED;
        return ASYNC_COMPLETE;
    }
    if (errno == EINPROGRESS || errno == EWOULDBLOCK || errno == EAGAIN) {
        ac->state = CONNECT_CONNECTING;
        /* The socket will be marked writable for select() when the
         * connection is established, or when it is definitely
         * refused / timed-out, for any reason. */
        loopIo_wantWrite(io);
        return ASYNC_NEED_MORE;
    }
    ac->error = errno;
    ac->state = CONNECT_ERROR;
    return ASYNC_ERROR;
}
Exemple #29
0
int	irc_dcc_accept (irc_session_t * session, irc_dcc_t dccid, void * ctx, irc_dcc_callback_t callback)
{
	irc_dcc_session_t * dcc = libirc_find_dcc_session (session, dccid, 1);

	if ( !dcc )
		return 1;

	if ( dcc->state != LIBIRC_STATE_INIT )
	{
		session->lasterror = LIBIRC_ERR_STATE;
		libirc_mutex_unlock (&session->mutex_dcc);
		return 1;
	}

	dcc->cb = callback;
	dcc->ctx = ctx;

	// Initiate the connect
    if ( socket_connect (&dcc->sock, (struct sockaddr *) &dcc->remote_addr, sizeof(dcc->remote_addr)) )
	{
		libirc_dcc_destroy_nolock (session, dccid);
		libirc_mutex_unlock (&session->mutex_dcc);
		session->lasterror = LIBIRC_ERR_CONNECT;
		return 1;
	}

	dcc->state = LIBIRC_STATE_CONNECTING;
	libirc_mutex_unlock (&session->mutex_dcc);
	return 0;
}
Exemple #30
0
void* dowork(void *arg){
    sqlite3 *db;
    int err = sqlite3_open_v2(GlobalArgs.dbname, &db,\
              SQLITE_OPEN_READWRITE|SQLITE_OPEN_SHAREDCACHE, NULL);
    if (db == NULL || err != SQLITE_OK){
	syslog(LOG_CRIT,"ERROR: unable to open db, error = %d",err);
	exit(1);
    }

    void *ctx = arg;
    if (!ctx){
	syslog(LOG_CRIT,"ERROR: no zmq context available to thread");
	exit(1);
    }

    void *skt = socket_connect(ctx, ZMQ_REP, "inproc://pipe");
    if (!skt){
	syslog(LOG_CRIT,"ERROR: no socket available for thread");
	exit(1);
    }

    while (1){
	err = handle_request(skt, db);
	if (err < 0){
	    syslog(LOG_DEBUG,"dowork: msg non-conformant to msg sizes, err=%d",err);
	}
    }
    
    return NULL;
}