Пример #1
0
bool SSLClient::connection(const string& host, const int& port)
{
	if(host=="localhost")
	{
		return connectionUnresolv(host, port);
	}

	struct sockaddr_in *remote;
	int tmpres;
	char *ip;

	sockfd = create_tcp_socket();
	ip = get_ip((char*)host.c_str());
	fprintf(stderr, "IP is %s\n", ip);
	remote = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in *));
	remote->sin_family = AF_INET;
	tmpres = inet_pton(AF_INET, ip, (void *)(&(remote->sin_addr.s_addr)));
	if( tmpres < 0)
	{
		perror("Can't set remote->sin_addr.s_addr");
		return false;
	}
	else if(tmpres == 0)
	{
		fprintf(stderr, "%s is not a valid IP address\n", ip);
		return false;
	}
	remote->sin_port = htons(port);

	if(connect(sockfd, (struct sockaddr *)remote, sizeof(struct sockaddr)) < 0){
		perror("Could not connect");
		connected = false;
	} else {
		connected = true;
	}

	free(remote);
	free(ip);

	/* Build our SSL context*/
	init();

	/* Connect the SSL socket */
	ssl=SSL_new(ctx);
	sbio=BIO_new_socket(sockfd,BIO_CLOSE);
	SSL_set_bio(ssl,sbio,sbio);
	io=BIO_new(BIO_f_buffer());
	ssl_bio=BIO_new(BIO_f_ssl());
	BIO_set_ssl(ssl_bio,ssl,BIO_NOCLOSE);
	BIO_push(io,ssl_bio);

	if(SSL_connect(ssl)<=0)
	{
		logger << "SSL connect error";
		return false;
	}
	ERR_clear_error();
	connected = true;
	return true;
}
Пример #2
0
int main()
{
  // sock: the socket.
  int sock = create_tcp_socket();

  // remote: a record of an input socket address.
  struct sockaddr_in* remote =
    (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in *));
  remote->sin_family = AF_INET;
  host = argv[1];
  char* ip = get_ip(host);
  int tmp_res = inet_pton(AF_INET, ip, (void*) (&(remote->sin_addr.s_addr)));
  if (tmp_res < 0) {
    fprintf(stderr, "inet_pton failed\n");
    exit(1);
  }
  remote->sin_port = htons(PORT);

  // Connect the socket to the remote host.
  if (connect(sock, (struct sockaddr*) remote, sizeof(struct sockaddr)) < 0) {
    fprintf(stderr, "connect failed\n");
    exit(0);
  }

  printf("connected successfully to remote host\n");
  return;
}
Пример #3
0
void test1()
{
	Sleep(5000);

	struct sockaddr_in addr;
	uv_tcp_t client;
	uv_os_sock_t sock;
	int r;

	//int nRet = uv_ip4_addr("127.0.0.1", 1234, &addr);
	TEST_ASSERT(0 == uv_ip4_addr("127.0.0.1", 1234, &addr));

	startup();
	sock = create_tcp_socket();

	r = uv_tcp_init(uv_default_loop(), &client);
	TEST_ASSERT(r == 0);

	r = uv_tcp_open(&client, sock);
	TEST_ASSERT(r == 0);

	r = uv_tcp_connect(&connect_req,
		&client,
		(const struct sockaddr*) &addr,
		connect_cb);
	TEST_ASSERT(r == 0);

	uv_run(uv_default_loop(), UV_RUN_DEFAULT);

// 	ASSERT(shutdown_cb_called == 1);
// 	ASSERT(connect_cb_called == 1);
// 	ASSERT(write_cb_called == 1);
// 	ASSERT(close_cb_called == 1);

}
Пример #4
0
/*
 * Initializes a connection with the server
 */
void init_connection(char* serv_ip, unsigned short serv_port)
{
	create_tcp_socket(&client_sock);
	printf("Created TCP socket\n");

	/* Construct the server address structure */
	memset(&serv_addr, 0, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	printf("Constructed server address structure\n");

	/* Convert address */
	int ret_val = inet_pton(AF_INET, serv_ip, &serv_addr.sin_addr.s_addr);
	if(ret_val <= 0) {
		switch_state(ERROR_STATE);
	}
	serv_addr.sin_port = htons(serv_port);
	printf("Converted address\n");

	/* Establish connection */
	if(connect(client_sock, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) {
		printf("conn fail\n");
		switch_state(ERROR_STATE);
	}
	printf("Established connection\n");
}
Пример #5
0
int htsp_connect(struct htsp_t* htsp)
{
    int res;

    htsp->sock = create_tcp_socket();
    if (htsp->ip == NULL)
      htsp->ip = get_ip(htsp->host);

    fprintf(stderr,"Connecting to %s (%s) port %d...\n",htsp->host,htsp->ip,htsp->port);    

    htsp->remote = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in));
    htsp->remote->sin_family = AF_INET;

    res = inet_pton(AF_INET, htsp->ip, (void *)(&(htsp->remote->sin_addr.s_addr)));

    if (res < 0) {
        perror("Can't set remote->sin_addr.s_addr");
        exit(1);
    } else if (res == 0) {
        fprintf(stderr, "%s is not a valid IP address\n", htsp->ip);
        return 1;
    }
    htsp->remote->sin_port = htons(htsp->port);
 
    if (connect(htsp->sock, (struct sockaddr *)htsp->remote, sizeof(struct sockaddr)) < 0){
        perror("Could not connect");
        return 2;
    }

    return 0;
}
Пример #6
0
static void *heartbeat()
{
	dfs_cm_datanode_status_t datanode_status;
	datanode_status.datanode_id = datanode_id;
	datanode_status.datanode_listen_port = datanode_listen_port;

	struct sockaddr_in namenode_addr;

	memset((void *)&namenode_addr, 0, sizeof(namenode_addr));
		
	//TODO: set nn_addr
	namenode_addr.sin_family = AF_INET;
	namenode_addr.sin_addr.s_addr = inet_addr(nn_ip);
	namenode_addr.sin_port = htons(50030); // hardcode

	assert(namenode_addr.sin_port == htons(50030)); 

	printf("dfs_datanode.c: heartbeat(): About to enter for loop. \n");

	for (;;)
	{
		int heartbeat_socket = -1;
		//TODO: create a socket to the namenode, assign file descriptor id to heartbeat_socket
		heartbeat_socket = create_tcp_socket();
		assert(heartbeat_socket != INVALID_SOCKET);
		
		// Send datanode status to namenode
		if (connect(heartbeat_socket, (struct sockaddr *) &namenode_addr, sizeof(namenode_addr)) == -1) printf("dfs_datanode.c: heartbeat: Connect error. \n");
		if (send(heartbeat_socket, &datanode_status, sizeof(datanode_status), 0) == -1) printf("dfs_datanode.c: heartbeat: Send error. \n");

		close(heartbeat_socket);
		sleep(HEARTBEAT_INTERVAL);
	}
}
Пример #7
0
        error_code hpc_network_provider::start(rpc_channel channel, int port, bool client_only, io_modifer& ctx)
        {
            if (_listen_fd != -1)
                return ERR_SERVICE_ALREADY_RUNNING;

            _looper = get_io_looper(node(), ctx.queue, ctx.mode);

            dassert(channel == RPC_CHANNEL_TCP || channel == RPC_CHANNEL_UDP,
                "invalid given channel %s", channel.to_string());

            char hostname[128];
            gethostname(hostname, sizeof(hostname));
            _address = ::dsn::rpc_address(HOST_TYPE_IPV4, hostname, port);

            if (!client_only)
            {
                struct sockaddr_in addr;
                addr.sin_family = AF_INET;
                addr.sin_addr.s_addr = INADDR_ANY;
                addr.sin_port = htons(port);

                _listen_fd = create_tcp_socket(&addr);
                if (_listen_fd == -1)
                {
                    dassert(false, "cannot create listen socket");
                }

                int forcereuse = 1;
                if (setsockopt(_listen_fd, SOL_SOCKET, SO_REUSEADDR,
                    (char*)&forcereuse, sizeof(forcereuse)) != 0)
                {
                    dwarn("setsockopt SO_REUSEDADDR failed, err = %s", strerror(errno));
                }

                if (listen(_listen_fd, SOMAXCONN) != 0)
                {
                    dwarn("listen failed, err = %s", strerror(errno));
                    return ERR_NETWORK_START_FAILED;
                }

                _accept_event.callback = [this](int err, uint32_t size, uintptr_t lpolp)
                {
                    this->do_accept();
                };

                // bind for accept
                _looper->bind_io_handle((dsn_handle_t)(intptr_t)_listen_fd, &_accept_event.callback,
                    EVFILT_READ,
                    nullptr // network_provider is a global object
                    );
            }

            return ERR_OK;
        }
Пример #8
0
        rpc_session_ptr hpc_network_provider::create_client_session(::dsn::rpc_address server_addr)
        {
            struct sockaddr_in addr;
            addr.sin_family = AF_INET;
            addr.sin_addr.s_addr = INADDR_ANY;
            addr.sin_port = 0;

            auto sock = create_tcp_socket(&addr);
            auto client = new hpc_rpc_session(sock, new_message_parser(), *this, server_addr, true);
            rpc_session_ptr c(client);
            client->bind_looper(_looper);
            return c;
        }
Пример #9
0
int main(int argc, char *argv[])
{
    int s, ns;
    int semaphore_id;
    int shared_memory_id = 0;
    uint16_t port;
    pid_t pid;
    struct sockaddr_in client;
    char *tmp_shm_addr;
    shm_t *g_shm;

    check_args(&argc, argv, 0);

    port = (uint16_t) atoi(argv[1]);
    create_tcp_socket(&s, port);

    semaphore_id = semaphore_new(SEM_KEY);
    v(semaphore_id, 1);

    shared_memory_id = create_shared_memory(SHM_KEY);
    tmp_shm_addr = associate_shared_memory(shared_memory_id);
    g_shm = (shm_t *) tmp_shm_addr;


    while (true) {

        accept_new_connection(&s, &ns, &client);

        if ((pid = fork()) == 0)

            shandler(&ns, semaphore_id, client, g_shm);

        else {
            if (pid > 0)

                fprintf(stderr, "#%d# Father - Created child process: %d\n", getpid(), pid);

            else {
                fprintf(stderr, "The fork() function has failed: %s!\n", strerror(errno));
                shared_memory_destroy(shared_memory_id);
                semaphore_destroy(semaphore_id);
                exit(EXIT_FAILURE);
            }
        }
    }

    shared_memory_destroy(shared_memory_id);
    semaphore_destroy(semaphore_id);

    exit(EXIT_SUCCESS);
}
Пример #10
0
/**
 * create the socket and connect it to the destination address
 * return the socket fd
 */
int create_client_tcp_socket(char* address, int port)
{
    assert(port >= 0 && port < 65536);
    int socket = create_tcp_socket();
    if (socket == INVALID_SOCKET) return 1;
    struct sockaddr_in serv_addr;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(port);
    serv_addr.sin_addr.s_addr = inet_addr(address);
    if(connect(socket, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0) {
        return -1;
    }
    return socket;
}
Пример #11
0
long redrobd_rc_net_server_thread::setup(void)
{
  try {
    redrobd_log_writeln(get_name() + " : setup started");

    // Create server socket
    if (create_tcp_socket(&m_server_sd) != SOCKET_SUPPORT_SUCCESS) {
      THROW_EXP(REDROBD_INTERNAL_ERROR, REDROBD_SOCKET_OPERATION_FAILED,
		"Create server socket failed in thread %s",
		get_name().c_str());
    }

    // Create socket address
    socket_address server_sa;
    if (to_net_address(m_server_ip_address.c_str(),
		       &server_sa.net_addr) != SOCKET_SUPPORT_SUCCESS) {
      THROW_EXP(REDROBD_INTERNAL_ERROR, REDROBD_SOCKET_OPERATION_FAILED,
		"Create server socket address failed in thread %s",
		get_name().c_str());
    }
    server_sa.port = m_server_port;

    // Bind socket to local address and port
    if (bind_socket(m_server_sd,
		    server_sa) != SOCKET_SUPPORT_SUCCESS) {
      THROW_EXP(REDROBD_INTERNAL_ERROR, REDROBD_SOCKET_OPERATION_FAILED,
		"Bind server socket failed in thread %s",
		get_name().c_str());
    }

    // Mark socket as accepting connections
    if (listen_socket(m_server_sd, 0) != SOCKET_SUPPORT_SUCCESS) {
      THROW_EXP(REDROBD_INTERNAL_ERROR, REDROBD_SOCKET_OPERATION_FAILED,
		"Listen server socket failed in thread %s",
		get_name().c_str());
    }
            
    redrobd_log_writeln(get_name() + " : setup done");

    return THREAD_SUCCESS;    
  }
  catch (excep &exp) {
    syslog_error(redrobd_error_syslog_string(exp).c_str());
    return THREAD_INTERNAL_ERROR;
  }
  catch (...) {
    syslog_error("redrobd_rc_net_server_thread::setup->Unexpected exception");
    return THREAD_INTERNAL_ERROR;
  }
}
Пример #12
0
/**
 * This function will initialize the connection and stuff
 */
void init_process() {

	signal(SIGCHLD, SIG_IGN);
	memset(client_udp_ports, 0, sizeof(client_udp_ports));
	//4. Create shared memory area with the child processes.
	// REUSED CODE :- http://www.tldp.org/LDP/lpg/node81.html
	//--START
	key_t key;

	/* Create unique key via call to ftok() */
	key = ftok("./test", 'S');

	if ((shmid = shmget(key, SEGSIZE, IPC_CREAT | 0666)) < 0) {
		perror("shmget");
		exit(1);
	}

	/* Attach (map) the shared memory segment into the current process */
	if ((segptr = (char *) shmat(shmid, NULL, 0)) == (char *) -1) {
		perror("shmat");
		exit(1);
	}

	//--END

	//3. set up TCP server at manager
	tcp_serv_sock_fd = create_tcp_socket();
	populate_sockaddr_in(&client_tcp_server, "localhost", 0);
	if (bind_address(tcp_serv_sock_fd, client_tcp_server) < 0) {
		perror("Error biding the address to socket. Exiting!!");
		exit(0);
	}

	//get the port number information
	socklen_t size = sizeof(tmp);
	if (getsockname(tcp_serv_sock_fd, (struct sockaddr *) &tmp, &size) < 0) {
		perror("Error getting port number information!!");
		exit(0);
	}

	//listen for incomming connections
	listen(tcp_serv_sock_fd, BACKLOG_QUEUE);

	//5. Put manager's port # in shared memory so that child processes and use it to connect the manager (server) socket
	//writeshm(segptr, temp);
	sprintf(segptr, "%u", ntohs(tmp.sin_port));
	printf("init_process: data set in shared memory is: %s\n", segptr);
}
Пример #13
0
/**
 * create a socket listening on the certain local port and return
 */
int create_server_tcp_socket(int port)
{
    assert(port >= 0 && port < 65536);
    int socket = create_tcp_socket();
    if (socket == INVALID_SOCKET) return 1;
    //TODO: listen on local port
    struct sockaddr_in serv_addr;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(port);
    bind(socket, (struct sockaddr*)&serv_addr,sizeof(serv_addr));
    if(listen(socket, 10) == -1) {
        return -1;
    }
    return socket;
}
Пример #14
0
error_code hpc_network_provider::start(rpc_channel channel, int port, bool client_only, io_modifer& ctx)
{
    if (_listen_fd != INVALID_SOCKET)
        return ERR_SERVICE_ALREADY_RUNNING;

    _looper = get_io_looper(node(), ctx.queue, ctx.mode);

    dassert(channel == RPC_CHANNEL_TCP || channel == RPC_CHANNEL_UDP,
            "invalid given channel %s", channel.to_string());

    char name[128];
    gethostname(name, sizeof(name));
    _address = ::dsn::rpc_address(HOST_TYPE_IPV4, name, port);

    if (!client_only)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_port = htons(port);

        _listen_fd = create_tcp_socket(&addr);
        if (_listen_fd == INVALID_SOCKET)
        {
            dassert(false, "");
        }

        int forcereuse = 1;
        if (setsockopt(_listen_fd, SOL_SOCKET, SO_REUSEADDR,
                       (char*)&forcereuse, sizeof(forcereuse)) != 0)
        {
            dwarn("setsockopt SO_REUSEDADDR failed, err = %d", ::GetLastError());
        }

        _looper->bind_io_handle((dsn_handle_t)_listen_fd, &_accept_event.callback);

        if (listen(_listen_fd, SOMAXCONN) != 0)
        {
            dwarn("listen failed, err = %d", ::GetLastError());
            return ERR_NETWORK_START_FAILED;
        }

        do_accept();
    }

    return ERR_OK;
}
Пример #15
0
        rpc_session_ptr hpc_network_provider::create_client_session(const ::dsn::rpc_address& server_addr)
        {
            auto matcher = new_client_matcher();
            auto parser = new_message_parser();

            struct sockaddr_in addr;
            addr.sin_family = AF_INET;
            addr.sin_addr.s_addr = INADDR_ANY;
            addr.sin_port = 0;

            auto sock = create_tcp_socket(&addr);
            dassert(sock != -1, "create client tcp socket failed!");
            auto client = new hpc_rpc_session(sock, parser, *this, server_addr, matcher);
            rpc_session_ptr c(client);
            client->bind_looper(_looper, true);
            return c;
        }
Пример #16
0
bool Client::connection(string host,int port)
{
	if(host=="localhost")
	{
		return connectionUnresolv(host, port);
	}

	struct sockaddr_in *remote;
	int tmpres;
	char *ip;

	sockfd = create_tcp_socket();
	ip = get_ip((char*)host.c_str());
	fprintf(stderr, "IP is %s\n", ip);
	remote = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in *));
	remote->sin_family = AF_INET;
	tmpres = inet_pton(AF_INET, ip, (void *)(&(remote->sin_addr.s_addr)));
	if( tmpres < 0)
	{
		perror("Can't set remote->sin_addr.s_addr");
		return false;
	}
	else if(tmpres == 0)
	{
		fprintf(stderr, "%s is not a valid IP address\n", ip);
		return false;
	}
	remote->sin_port = htons(port);

	if(connect(sockfd, (struct sockaddr *)remote, sizeof(struct sockaddr)) < 0){
		perror("Could not connect");
		connected = false;
	} else {
		connected = true;
	}
	free(remote);
	free(ip);
	
	return connected;
}
Пример #17
0
void hpc_network_provider::do_accept()
{
    socket_t s = create_tcp_socket(nullptr);
    dassert(s != INVALID_SOCKET, "cannot create socket for accept");

    _accept_sock = s;
    _accept_event.callback = [this](int err, uint32_t size, uintptr_t lpolp)
    {
        //dinfo("accept completed, err = %d, size = %u", err, size);
        dassert(&_accept_event.olp == (LPOVERLAPPED)lpolp, "must be this exact overlap");
        if (err == ERROR_SUCCESS)
        {
            setsockopt(_accept_sock,
                       SOL_SOCKET,
                       SO_UPDATE_ACCEPT_CONTEXT,
                       (char *)&_listen_fd,
                       sizeof(_listen_fd)
                      );

            struct sockaddr_in addr;
            memset((void*)&addr, 0, sizeof(addr));

            addr.sin_family = AF_INET;
            addr.sin_addr.s_addr = INADDR_ANY;
            addr.sin_port = 0;

            int addr_len = sizeof(addr);
            if (getpeername(_accept_sock, (struct sockaddr*)&addr, &addr_len)
                    == SOCKET_ERROR)
            {
                dassert(false, "getpeername failed, err = %d", ::WSAGetLastError());
            }

            ::dsn::rpc_address client_addr;
            dsn_address_build_ipv4(client_addr.c_addr_ptr(), ntohl(addr.sin_addr.s_addr), ntohs(addr.sin_port));

            auto parser = new_message_parser();
            auto s = new hpc_rpc_session(_accept_sock, parser, *this, client_addr);
            rpc_session_ptr s1(s);
            s->bind_looper(_looper);

            this->on_server_session_accepted(s1);

            s->do_read();
        }
        else
        {
            closesocket(_accept_sock);
        }

        do_accept();
    };
    memset(&_accept_event.olp, 0, sizeof(_accept_event.olp));

    DWORD bytes;
    BOOL rt = s_lpfnAcceptEx(
                  _listen_fd, s,
                  _accept_buffer,
                  0,
                  (sizeof(struct sockaddr_in) + 16),
                  (sizeof(struct sockaddr_in) + 16),
                  &bytes,
                  &_accept_event.olp
              );

    if (!rt && (WSAGetLastError() != ERROR_IO_PENDING))
    {
        dassert(false, "AcceptEx failed, err = %d", ::WSAGetLastError());
        closesocket(s);
    }
}
Пример #18
0
int getHTML(char *domainName, char *webPageFolder, char* sourceOutput){

   struct sockaddr_in *remote;
   int sock, tmpres;
   char *ip, *get, buf[BUFSIZ+1], *host, *page;

   host = domainName;
   page = (webPageFolder !=NULL)?webPageFolder:PAGE;
  
   sock = create_tcp_socket();
   ip = get_ip(host);
   fprintf(stderr, "IP is %s\n", ip); 
   remote = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in *));
   remote->sin_family = AF_INET;
   tmpres = inet_pton(AF_INET, ip, (void *)(&(remote->sin_addr.s_addr)));

   if( tmpres < 0) {
      perror("Can't set remote->sin_addr.s_addr");
      exit(1);
   } else if(tmpres == 0) {
      fprintf(stderr, "%s is not a valid IP address\n", ip);
      exit(1);
   }

   remote->sin_port = htons(PORT);

   if(connect(sock, (struct sockaddr *)remote, sizeof(struct sockaddr)) < 0){
      perror("Could not connect");
      exit(1);
   }
  
   get = build_get_query(host, page);
   fprintf(stderr, "Query is:\n<<START>>\n%s<<END>>\n", get);
  
   //Send the query to the server
   int sent = 0;
   while(sent < strlen(get))  { 
     tmpres = send(sock, get+sent, strlen(get)-sent, 0);
     if(tmpres == -1){
       perror("Can't send query");
       exit(1);
     }
     sent += tmpres;
   }

   //Now read in the source code returned
   memset(buf, 0, sizeof(buf));
   int n, buflen = BUFSZ;
   char *pbuf = sourceOutput;
   while ((n = recv(sock, pbuf, buflen, 0)) > 0){
      pbuf += n;
      buflen -= n;
   }

   if(n < 0)  {
      perror("Error receiving data");
   }

   free(get);
   free(remote);
   free(ip);
   close(sock);
   return 0;
}
Пример #19
0
int main(int argc,char **argv)
{

	server *srv=NULL;
	
	//step 1 : initialize server
	if( (srv= server_init()) ==NULL){
		fprintf(stderr,"failed to initialize server in [%s|%d|%s]\n",__FILE__,__LINE__,__FUNCTION__);
		return -1;		
	}	
	//step 2 : parameter parse
	char opt_chr;
	while(  (opt_chr=getopt(argc,argv,"f:hvD"))!=-1 ){
		switch(opt_chr){
			/*configuration file path */
		    case 'f':{
				        buffer_copy_string(srv->config->minihttpd_global_config_filepath,optarg);
				        break;
			}
		   /* show help */
		   case 'h':{
			            print_help();
						server_free(srv);
						return 0;
		   }
		  case 'v':{
			       fprintf(stdout,"%s-%s",srv->config->service_name->ptr,srv->config->version_info->ptr);
				   server_free(srv);
			       return 0;
		   }
		  case 'D':{
			         srv->dont_daemonize=1;
			         break;			
		  }
		  default:{
			        print_help();
			        server_free(srv);
					return -1;
		  }				
		}		
 	}

    //step 3 :check if all configuraiton is legal
	if(buffer_is_empty(srv->config->service_root_dir)){
		fprintf(stderr,"[%s|%d|%s]:please specify minihttp root dir in configuration file\n",
				 __FILE__,__LINE__,__FUNCTION__);
		server_free(srv);
		return -1;		
	}	
    /*parse the mime configuration file */
	if(buffer_is_empty(srv->config->mimetype_filepath)
	   ||   (srv->config->table= mime_table_initialize( (const char*)srv->config->mimetype_filepath->ptr) )==NULL){
        fprintf(stderr,"invalid mime configuration file is specified,pls check it..\n");
		server_free(srv);
		return -1;
	}

	//step4 :server started
    srv->uid=getuid();
	srv->gid=getgid();
	if(srv->uid==0) {  //we are root 
		struct rlimit res_limit;
		if(getrlimit(RLIMIT_NOFILE,&res_limit)!=0){
            fprintf(stderr,"[%s|%d|%s]: failed to get file descriptor max number for current process!\n",
					__FILE__,__LINE__,__FUNCTION__);
			server_free(srv);
			return -1;			
		}

		res_limit.rlim_cur=srv->config->max_fd;
		res_limit.rlim_max=srv->config->max_fd;
		
		if(setrlimit(RLIMIT_NOFILE,&res_limit)!=0){
			fprintf(stderr,"[%s|%d|%s]: failed call setrlimit(RLIMIT_NOFILE,) for current process!\n",
					__FILE__,__LINE__,__FUNCTION__);
			server_free(srv);
			return -1;			
		}     		
	}else{
		struct rlimit res_limit;
		if(getrlimit(RLIMIT_NOFILE,&res_limit)!=0){

			fprintf(stderr,"[%s|%d|%s]: failed to get file descriptor max number for current process!\n",
					__FILE__,__LINE__,__FUNCTION__);
			server_free(srv);
			return -1;				
		}

		if(srv->config->max_fd< res_limit.rlim_cur)
			res_limit.rlim_cur=srv->config->max_fd;
		else if(srv->config->max_fd<=res_limit.rlim_max)
			res_limit.rlim_cur=srv->config->max_fd;

		if(setrlimit(RLIMIT_NOFILE,&res_limit)!=0){
            fprintf(stderr,"[%s|%d|%s]: failed call setrlimit(RLIMIT_NOFILE,) for current process!\n",
				__FILE__,__LINE__,__FUNCTION__);
			server_free(srv);
			return -1;			 
		}
	}

	//step 5:  become a daemon process if dont_daemonize=0;
	if(!srv->dont_daemonize){
        daemonize((const char*)srv->config->service_name->ptr); 		 
	}
	//step 6: open log file for error log, by default we use syslog.
	// if the minihttpd log filepath is specified manually or server dont_daemonize=1,
	// we set mode = LOG_MODE_FILE;
	
	if(!buffer_is_empty(srv->config->log_filename) || srv->dont_daemonize ){
		if(buffer_is_empty(srv->config->log_filename))
			buffer_copy_string(srv->config->log_filename,MINIHTTPD_DEFAULT_LOG_FILEPATH);
		
		srv->log_fd= open((const char*)srv->config->log_filename->ptr,O_WRONLY|O_CREAT|O_TRUNC,
						  S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
		if(srv->log_fd<0){
			server_free(srv);
			return -1;
		}
		fd_close_on_exec(srv->log_fd);
        srv->mode=server::LOG_MODE_FILE;			
	}
	log_to_backend(srv,MINIHTTPD_LOG_LEVEL_INFO,"%s is start now...",(const char*)srv->config->service_name->ptr);
	
	//step 7 : create listening tcp socket(we only support ipv4 now)
    struct sockaddr_in * addr= (struct sockaddr_in*)&srv->server_addr;
	memset(addr,0,sizeof(*addr));
	addr->sin_family=AF_INET;
	addr->sin_addr.s_addr=htonl(INADDR_ANY);
	addr->sin_port=htons(srv->config->listenint_port);
	srv->listening_socket_fd= create_tcp_socket((struct sockaddr*)addr,srv->config->max_listening_number);
	if(srv->listening_socket_fd<0){
        log_to_backend(srv, MINIHTTPD_LOG_LEVEL_ERROR,"failed to create listening tcp socket on port:%d",
							 srv->config->listenint_port);
		server_free(srv);
		return -1;
	}

	 /*
	    step 8:  setup signal  handler
		signo: SIGCHLD
		signo: SIGPIPE: unix domain socket pipe is broken
		signo: SIGINT:  user intend to shutdown the minihttpd server
		                if SIGINT is kill to the server proces for twice, the minihtpd server is going to shutdown
		signo: SIGTERM: exit minihttpd service now 				
	 */
	struct sigaction act;
	sigemptyset(&act.sa_mask);
	act.sa_flags=0;
	act.sa_handler=signal_handler;
	sigaction(SIGPIPE,&act,NULL);
	sigaction(SIGCHLD,&act,NULL);
    sigaction(SIGINT,&act,NULL);
	sigaction(SIGTERM,&act,NULL);
	
	/*
	     step 9: fork worker child process  and transfter accept socket file descriptor to worker process
		 the only tasks for main processis :
		        1) to call accept to wait for connection and pick one worker process to handle the connection  
				2) wait all worker  process to finish before exit.
   */
    
	for(uint32_t worker_process_id=0;worker_process_id< srv->worker_number ;worker_process_id++) {
		server_child * child= &srv->child[worker_process_id];
		
		//create unix domain socket 
		if(socketpair(AF_UNIX,SOCK_STREAM,0,child->unix_domain_socket_fd)<0){
			log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"failed to create unix domain socket for worker%d",
						  worker_process_id);
			close(srv->listening_socket_fd);
			server_free(srv);
			return -1;			
		}
        child->sent_connection_number=0;
		int unix_domain_socket_child_fd=child->unix_domain_socket_fd[1];
		fd_set_nonblocking(unix_domain_socket_child_fd);
		child->pid=fork();
		
		if(child->pid <0){   //we can not fork worker process, this should not be happened
			close(srv->listening_socket_fd);
			server_free(srv) ;
			return -1;
		}
		else if(child->pid ==0) {   /*  worker process */ 
            /*we should use p_worker only in the child worker process */
#if 0
			minihttpd_running_log(srv->log_fd,MINIHTTPD_LOG_LEVEL_INFO,__FILE__,__LINE__,__FUNCTION__,
								  "worker(pid=%d) is starting.....",getpid());
#endif 	
			worker * server_worker =  (worker*)malloc(sizeof(worker));
			memset(server_worker,0,sizeof(worker));
            server_worker->worker_id= worker_process_id;
			server_worker->unix_domain_socekt_fd=unix_domain_socket_child_fd;
			server_worker->log_filepath=buffer_init();
			server_worker->global_config= srv->config;
			/*step1 : get current file descriptor max number (it should be same as parent process
			                               which we have set the resouces)*/
		    struct rlimit limit;
			if(getrlimit(RLIMIT_NOFILE,&limit)<0){
				exit(-1);  // terminated the worker   				
			}
			//close unnecessary file descriptor
			for(uint32_t file_descriptor_index=0;file_descriptor_index< limit.rlim_cur;file_descriptor_index++){
				if(file_descriptor_index> STDERR_FILENO && file_descriptor_index != unix_domain_socket_child_fd){
					close(file_descriptor_index);					
				}
			}
			
			//step 2: set event handler
			server_worker->ev= fdevent_initialize(limit.rlim_cur);
            /*support max connection number */
			uint32_t worker_support_max_connections=limit.rlim_cur/2;
			worker_connection_initialize(server_worker, worker_support_max_connections);
			
			//step 3 : register unix domain socket event
			fdevents_register_fd(server_worker->ev,server_worker->unix_domain_socekt_fd,
								 unix_domain_socket_handle,server_worker);
			//EPOLLHUP |EPOLLERR events is set by default
			fdevents_set_events(server_worker->ev,server_worker->unix_domain_socekt_fd,EPOLLIN); 

			//step 4 : open log file for worker to log debug/info/warning/error
            if(buffer_is_empty(server_worker->log_filepath)){
				char  worker_log_filepath[255];
				snprintf(worker_log_filepath,sizeof(worker_log_filepath),
						            MINIHTTPD_WORKER_CONFIG_PATH"%u.log", server_worker->worker_id );
				buffer_append_string(server_worker->log_filepath,worker_log_filepath);			   				
			}
			server_worker->log_fd= open((const char*)server_worker->log_filepath->ptr, O_WRONLY|O_CREAT|O_TRUNC,
				 S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
			if(server_worker->log_fd<0){
				exit(-2); 
			}
			//step 5 : setup timer and expect timer will expire with internal 1 seconds
			time(&server_worker->cur_ts);
			int timer_fd=timerfd_create(CLOCK_REALTIME,TFD_NONBLOCK);
			struct itimerspec timer_spec;
			timer_spec.it_value.tv_sec=1;
			timer_spec.it_value.tv_nsec=0;
			timer_spec.it_interval.tv_sec=1;
			timer_spec.it_interval.tv_nsec=0;
			timerfd_settime(timer_fd,0,&timer_spec,NULL);
			// setup timer experation events handler
			fdevents_register_fd(server_worker->ev, timer_fd,worker_timer_expire_handler,
				server_worker);
			fdevents_set_events(server_worker->ev,timer_fd,EPOLLIN);
			
			/* main loop for worker: epoll event loop for unix domain socket and connections */
			while(server_shutdown==0 || server_worker->cur_connection_number >0 ) {
				int n=epoll_wait(server_worker->ev->epoll_fd, server_worker->ev->epoll_events,
								 server_worker->ev->max_epoll_events,-1);
				if(n<0 ){
					if(errno!=EINTR){
						minihttpd_running_log(server_worker->log_fd,MINIHTTPD_LOG_LEVEL_ERROR
											  ,__FILE__,__LINE__,__FUNCTION__,
											  "failed to call epoll with errno=%d",errno);						
					}
					continue;
				}
				else if(n==0){
					//we should not get to here
					continue;					
				}else {

					for(uint32_t event_index=0;event_index<n;event_index++){
                        struct epoll_event * event= &server_worker->ev->epoll_events[event_index];
						assert(event!=NULL);
						int connection_socket_fd= event->data.fd;
						event_handle handler=fdevents_get_handle(server_worker->ev,connection_socket_fd);
						void * event_ctx=fdevents_get_context(server_worker->ev, connection_socket_fd);
						assert(handler!=NULL);
						int handle_status= handler(connection_socket_fd,event_ctx,event->events);
					    minihttpd_running_log(server_worker->log_fd,handle_status==0?
											  MINIHTTPD_LOG_LEVEL_INFO:MINIHTTPD_LOG_LEVEL_ERROR,
											  __FILE__,__LINE__,__FUNCTION__,"the epoll event is already handled!");
						

					}										
				}				
			}
			
			minihttpd_running_log(server_worker->log_fd,MINIHTTPD_LOG_LEVEL_INFO,
							  __FILE__,__LINE__,__FUNCTION__,"child worker process has finished all client requests!\n");

			/*free all connections */
			worker_free_connectons(server_worker);

			/* unregister timer file descriptor */
			fdevents_unset_event(server_worker->ev,timer_fd);
			fdevents_unregister_fd(server_worker->ev,timer_fd);
		    close(timer_fd);
            /* unregister unix domain socket hanlde events and handler context */
			fdevents_unset_event(server_worker->ev,server_worker->unix_domain_socekt_fd);
			fdevents_unregister_fd(server_worker->ev,server_worker->unix_domain_socekt_fd);
			close(server_worker->unix_domain_socekt_fd);
			
			/* free fevents resources  */
            close(server_worker->ev->epoll_fd);			
			fdevent_free(server_worker->ev);

			//close the log file
			close(server_worker->log_fd);
			buffer_free(server_worker->log_filepath);

			/* free worker */
			free( (void*) server_worker);
			exit(0);   //termianted the worker 
		}
		//close the unix domain socket worker file descriptor;
		close(child->unix_domain_socket_fd[1]);

		// child worker is running 
		child->worker_running=1;
		//parent process
		log_to_backend(srv,MINIHTTPD_LOG_LEVEL_INFO,"worker process %d is already created!",worker_process_id);
	}

    //main loop to accept client connection and re-transfter to worker process 
	while(!server_shutdown) {

         /*
             log signal events after signal si handled by signal handler   

		 */
		if(signal_pipe_handled){
            /* if unix domain socket pipe is broken and we still write data to the pipe  */
		    	
		}
		
		
		if(signal_child_handled){
			/*a child worker process has terminated */
			int worker_exit_status;
			pid_t exit_worker_pid;

			
			while( (exit_worker_pid= waitpid(-1,&worker_exit_status,WNOHANG))>0){

			  if(WIFEXITED(worker_exit_status)){	  
			    log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"worker child process(pid=%d) has exited normally with exit"  \
							  "status=%d",exit_worker_pid,WEXITSTATUS(worker_exit_status));
			  }	  
			  else if(WIFSIGNALED(worker_exit_status)){
				  log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"worker child process(pid=%d) is killed by signal(%d)",
								 exit_worker_pid,WTERMSIG(worker_exit_status))  
			  }
              else{
            		 log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"worker child process(pid=%d) has exited unexpected",                                      exit_worker_pid);
			  }

               //remove the worker from available worker list and do not send socket file descriptor to it
			  for(uint32_t child_worker_id=0;child_worker_id< srv->worker_number;child_worker_id++){
				  if(srv->child[child_worker_id].pid==exit_worker_pid)
					  srv->child[child_worker_id].worker_running=0;				  
			  }			 			 
		    }

		    signal_child_handled=0;
		}		
		//we block here to wait connection(only IPV4 is supported now ) 
		struct sockaddr_in client_addr;
		socklen_t client_addr_length=sizeof(client_addr);
		int connection_fd =accept(srv->listening_socket_fd,(struct sockaddr*)&client_addr,(socklen_t*)& client_addr_length);
		if(connection_fd<0){
			switch(errno){
			   case  EINTR:
				// the connection is reset by client
			   case ECONNABORTED:   
				                 continue;				   		  				
			   case  EMFILE:  //file descriptor is all used now, need to send file descriptor to worker soon
				             break;
			   default:  {
				   log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"failed to call accept() with errno=%d\n",errno);				 
				   break;				
			   }				
			}			
		}
		else{

          /*
		     pick up a worker process and send the @conneciton_fd to it
             the pick algorithm is round-robin,;
			 but for the draft version, we just pick a worker that we has sent the min connections  

		  */
 		 log_to_backend(srv,MINIHTTPD_LOG_LEVEL_INFO,"client connection is accepted,pick a worker to handle it.");
			
		 uint32_t  pick_worker_index= srv->worker_number;
		 uint32_t  min_sent_connections=0xFFFFFFFF;

         for(uint32_t worker_process_id=0; worker_process_id<srv->worker_number;worker_process_id++){
            if(srv->child[worker_process_id].sent_connection_number < min_sent_connections
			   &&  srv->child[worker_process_id].worker_running) {
				min_sent_connections= srv->child[worker_process_id].sent_connection_number;
				pick_worker_index= worker_process_id;
			}			
		 }
		 
		 if(pick_worker_index>= srv->worker_number){
			  /* we can not handle it as all child worker has exited...*/
			 close(connection_fd);
			 continue;
		 }
		 
		 /*set file descriptor to nonblocking and set close_on_exec flag*/
		 fd_set_nonblocking(connection_fd);
		 fd_close_on_exec(connection_fd);

		 if(unix_domain_socket_sendfd(srv->child[pick_worker_index].unix_domain_socket_fd[0],
									 connection_fd)<0){
			 log_to_backend(srv,MINIHTTPD_LOG_LEVEL_ERROR,"failed to send the connection file descriptor to worker!");
			 close(connection_fd);  //just close it to tell the client,we can not handle it now.
			 continue;			
		 }
		 srv->child[pick_worker_index].sent_connection_number++;
		 //close the file descriptor as it is already marked in flight
		 close(connection_fd);
	   }
	}
Пример #20
0
int main(int argc, char **argv) {
	struct sockaddr_in *remote;
	int tmpres;
	char *ip;
	char buf[BUFSIZ + 1];

	int port = PORT;

	if (argc > 1) {
		// Read the port number
		port = atoi(argv[1]);

		// read the times
		if (argc > 2) {
			int i = 2;

			while (i < argc) {
				times[i - 2] = atoi(argv[i]);
				fprintf(stderr, "times[i]   %i \n", times[i]);
				i++;
				maxImageCount++;
			}
		}
	}

	host = HOST;
	page = PAGE;

	sock = create_tcp_socket();
	ip = get_ip(host);
	int clientID = -1;		// set the clientID value to a non possible value for now.
	averageSendTime = -1;

	remote = (struct sockaddr_in *) malloc(sizeof(struct sockaddr_in *));
	remote->sin_family = AF_INET;
	tmpres = inet_pton(AF_INET, ip, (void *) (&(remote->sin_addr.s_addr)));
	if (tmpres < 0) {
		perror("Can't set remote->sin_addr.s_addr");
		exit(1);
	} else if (tmpres == 0) {
		fprintf(stderr, "%s is not a valid IP address\n", ip);
		exit(1);
	}
	remote->sin_port = htons(port);

	// CONNECT
	if (connect(sock, (struct sockaddr *) remote, sizeof(struct sockaddr))
			< 0) {
		perror("Could not connect");
		sleep(2);
		exit(1);
	}

	// Wait for server to tell you what your ID is.
	memset(buf, 0, sizeof(buf));
//	recv(sock, buf, BUFSIZ, 0);
	fprintf(stderr, "Got from Server: %s \n", buf);

	// Set the last send time  to now. So we dont send a image request to soon.
	sentImageCount = 0;
	clock_gettime(CLOCK_MONOTONIC, &lastSendTime);

	// Setup Sender thread
	pthread_t tid;
	int flag = pthread_create(&tid, /* id */
	NULL, /* attributes */
	send_request_on_time, NULL ); /* routine */

	if (flag < 0) {
		perror("Couldn't create thread");
	}

	// Recieve message code
	memset(buf, 0, sizeof(buf));
	int imagestart = 0;
	char * messageContent;
	fprintf(stderr, "Start recv \n");
	while ((tmpres = recv(sock, buf, BUFSIZ, 0)) > 0) {
		// Check for the ClientID message.
		const char* from = buf;
		char *clientIdHeaderTo = (char*) malloc(9);
		strncpy(clientIdHeaderTo, from, 9);
		int clientIDResult = strncmp(clientIdHeaderTo, "clientID:", 9);
		if (clientIDResult == 0)
		{
			char *clientIdValueTo = (char*) malloc(15);
			strncpy(clientIdValueTo, from+10, 15);
			clientID = atoi(clientIdValueTo);
			fprintf(stderr, "Found a client ID: %d \n", clientID);
		}



		if (imagestart == 0) {
			/* Under certain conditions this will not work.
			 * If the \r\n\r\n part is splitted into two messages
			 * it will fail to detect the beginning of HTML content
			 */
			fprintf(stderr, "Receive a page %s  \n", buf);
			messageContent = strstr(buf, "\r\n\r\n");
			if (messageContent != NULL ) {
				imagestart = 1;
				messageContent += 4;
			}
		} else {
			messageContent = buf;
		}
		if (imagestart) {
//			fprintf(stdout, messageContent);
		}

		memset(buf, 0, tmpres);
	}
	fprintf(stderr, "HTML content %s \n", messageContent);
	if (tmpres < 0) {
		perror("Error receiving data");
	}
	free(remote);
	free(ip);
	close(sock);

	sleep(1);
	return 0;
}
Пример #21
0
int main(int argc, char *argv[])
{
    ssl_init();
    OrderBook order_book(3);
    Orders<1000> orders;
    auto poller = Poller::create();

    Url diff_url("wss://ws.pusherapp.com/app/de504dc5763aeef9ff52?protocol=5");
    auto diff_socket = create_tcp_socket(diff_url.host(), 80);
    diff_socket->set_callbacks<DiffLogic<1000>>(std::ref(diff_url), std::ref(orders));
    poller->update_socket(diff_socket, EPOLLIN | EPOLLOUT);

    Url order_book_url("https://www.bitstamp.net/api/order_book");
    auto order_book_socket = create_tcp_socket(order_book_url.host(), 443);
    order_book_socket->set_callbacks<ReceiveOrderBookLogic>(std::ref(order_book_url), std::ref(order_book));
    poller->update_socket(order_book_socket, EPOLLOUT | EPOLLIN);

    //----------------------

    std::shared_ptr<Order> order;
    Timer reconect_timer;
    Timer update_timer;
    Timer stop_timer;
    stop_timer.reset();
    uint64_t last_time = 0;
    const uint64_t RECONECT_INTERVAL = 20;

    bool order_book_ready = false;

    for (;;)
    {
        poller->poll();

        for (;;)
        {
            auto event = poller->get_next_event();
            if (!event.action)
                break;

            try
            {
                if (event.action & PollerEvent::READ)
                    event.socket->read();

                if (event.action & PollerEvent::WRITE)
                    event.socket->write();

                if (event.action & PollerEvent::CLOSE)
                    event.socket->close(event.close_reason);
            }
            catch (const std::exception & e)
            {
                std::cerr << "Exception in callback: " << e.what() << std::endl << "Closing socket." << std::endl;
                event.socket->close();
            }
        }

        if (!order_book)
        {
            if (!order_book_socket.get() && reconect_timer.elapsed_seconds() > RECONECT_INTERVAL)
            {
                std::cerr << "creating new order_book_socket" << std::endl;
                order_book_socket = create_tcp_socket(order_book_url.host(), 443);
                order_book_socket->set_callbacks<ReceiveOrderBookLogic>(std::ref(order_book_url), std::ref(order_book));
                poller->update_socket(order_book_socket, EPOLLOUT | EPOLLIN);
            }

            continue;
        }

        if (!order_book_ready)
        {
            uint64_t first_diff_timestamp = orders.get_first_timestamp();
            uint64_t last_book_timestamp  = order_book.get_last_timestamp();

            std::cerr << first_diff_timestamp << "/" << last_book_timestamp << std::endl;

            if (last_book_timestamp < first_diff_timestamp)
            {
                order_book.clear();
                reconect_timer.reset();
                order_book_socket.reset();
                continue;
            }

            order_book_ready = true;
        }

        while (order = orders.get_order())
            order_book.add(*order);

        if (update_timer.elapsed_seconds() != last_time)
        {
            last_time = update_timer.elapsed_seconds();
            order_book.print();
        }
    }

    ssl_destroy();
    return 0;
}
Пример #22
0
int main(int argc, char **argv)
{
  struct sockaddr_in *remote;
  int sock;
  int tmpres;
  char *ip;
  char *get;
  char buf[BUFSIZ+1];
  char *host;
  char page[URL_MAX_SIZE];
  char json_res[RES_MAX_SIZE];

  if(argc != 2){
    usage();
    exit(2);
  }  

  host = HOST;
  if(argc == 2){
    snprintf(page, URL_MAX_SIZE,"%s%s", SEARCH_URL,argv[1]);
  }

  sock = create_tcp_socket();
  ip = get_ip(host);
  fprintf(stderr, "IP is %s\n", ip);
  remote = (struct sockaddr_in *)malloc(sizeof(struct sockaddr_in *));
  remote->sin_family = AF_INET;
  tmpres = inet_pton(AF_INET, ip, (void *)(&(remote->sin_addr.s_addr)));
  if( tmpres < 0)  
  {
    perror("Can't set remote->sin_addr.s_addr");
    exit(1);
  }else if(tmpres == 0)
  {
    fprintf(stderr, "%s is not a valid IP address\n", ip);
    exit(1);
  }
  remote->sin_port = htons(PORT);
 
  if(connect(sock, (struct sockaddr *)remote, sizeof(struct sockaddr)) < 0){
    perror("Could not connect");
    exit(1);
  }
  get = build_get_query(host, page);
  fprintf(stderr, "Query is:\n<<START>>\n%s<<END>>\n", get);
 
  //Send the query to the server
  int sent = 0;
  while(sent < strlen(get))
  {
    tmpres = send(sock, get+sent, strlen(get)-sent, 0);
    if(tmpres == -1){
      perror("Can't send query");
      exit(1);
    }
    sent += tmpres;
  }
  //now it is time to receive the page
  memset(buf, 0, sizeof(buf));
  // Buffer for page chunks aggregation
  memset(json_res, 0, sizeof(json_res));

  int htmlstart = 0;
  char * htmlcontent;
  while((tmpres = recv(sock, buf, BUFSIZ, 0)) > 0){
    if(htmlstart == 0)
    {
      /* Under certain conditions this will not work.
      * If the \r\n\r\n part is splitted into two messages
      * it will fail to detect the beginning of HTML content
      */
      htmlcontent = strstr(buf, "\r\n\r\n");
      if(htmlcontent != NULL){
        htmlstart = 1;
        htmlcontent += 4;

      }
    }else{
      htmlcontent = buf;
    }
    if(htmlstart){
      /* fprintf(stdout, "%s", htmlcontent);*/
//     fprintf(stdout,"\n\njson2: %s, \n\nhtml2: %s\n\n",json_res, htmlcontent);
      strncat(json_res, htmlcontent, RES_MAX_SIZE);
	
    }
 
    memset(buf, 0, tmpres);
  }

//   fprintf(stdout, "%s", json_res);
   /* Parse JSON result */
   parseJSON(json_res);

  if(tmpres < 0)
  {
    perror("Error receiving data");
    return -1;
  }

  free(get);
  free(remote);
  free(ip);
  close(sock);
  return 0;
}
Пример #23
0
int main(int argc, char * argv[])
{
  struct spead_socket *x;
  struct spead_client *c;

  sslKeys_t *keys;
  int32 err;
  
  if (register_signals() < 0)
    return 1;

  x = create_tcp_socket(NULL, "3333");
  if (x == NULL)
    return 1;

  if (bind_spead_socket(x) < 0){
    destroy_spead_socket(x);
    destroy_shared_mem();
    return 1;
  }

  if (listen_spead_socket(x) < 0) {
    destroy_spead_socket(x);
    destroy_shared_mem();
    return 1;
  }

  err = matrixSslOpen();
  if (err != PS_SUCCESS){
#ifdef DEBUG
    fprintf(stderr, "%s: error setting up matrixssl\n", __func__);
#endif
    destroy_spead_socket(x);
    destroy_shared_mem();
    return 1;
  }

  err = matrixSslNewKeys(&keys);
  if (err != PS_SUCCESS){
#ifdef DEBUG
    fprintf(stderr, "%s: error allocationg matrixssl keys\n", __func__);
#endif
    destroy_spead_socket(x);
    destroy_shared_mem();
    matrixSslClose();
    return 1;
  }

  err = matrixSslLoadRsaKeys(keys, "./certs/server.crt", "./certs/server.key", NULL, NULL);
  if (err != PS_SUCCESS){
#ifdef DEBUG
    switch(err){
      case PS_CERT_AUTH_FAIL:
        fprintf(stderr, "Certificate or chain did not self-authenticate or private key could not authenticate certificate\n");
        break;
      case PS_PLATFORM_FAIL:
        fprintf(stderr, "Error locating or opening an input file\n");
        break;
      case PS_ARG_FAIL:
        fprintf(stderr, "Bad input function parameter\n");
        break;
      case PS_MEM_FAIL:
        fprintf(stderr, "Internal memory allocation failure\n");
        break;
      case PS_PARSE_FAIL:
        fprintf(stderr, "Error parsing certificate or private key buffer\n");
        break;
      case PS_FAILURE:
        fprintf(stderr, "Password protected decoding failed. Likey incorrect password provided\n");
        break;
      case PS_UNSUPPORTED_FAIL:
        fprintf(stderr, "Unsupported key algorithm in certificate material\n");
        break;
    }
#endif
    destroy_spead_socket(x);
    destroy_shared_mem();
    matrixSslDeleteKeys(keys);
    matrixSslClose();
    return 1;
  }


  while (run){
  
    c = accept_spead_socket(x);
    if (c){
      
      switch(fork()){
        case -1:
#ifdef DEBUG
          fprintf(stderr, "%s: fork err (%s)\n", __func__, strerror(errno));
#endif
          break;
        
        /*child*/
        case 0:
          /*child process takes over the accept object*/
          child_process(c, keys);
          exit(EXIT_SUCCESS);
          break;

        /*parent*/
        default:
#ifdef DEBUG
          fprintf(stderr, "%s: close the child fd on the parent\n", __func__);
#endif
          /*server closes the file descriptor and frees the object but doesn't 
            shutdown the connection from accept*/
          close(c->c_fd);
          free(c);
          break;
      }
    }

  }

  destroy_spead_socket(x);
  destroy_shared_mem();
  matrixSslDeleteKeys(keys);
  matrixSslClose();

  return 0;
}
Пример #24
0
/* Run Server
 *  Function tat will create a new socket, accept and handle connections from clients
 */
void run_server ( settings_t **settings, char* ( *callback ) ( char* ) ) {
    fd_set master;
    fd_set readSet;
    
    
    int listener;
    int new_fd;
    int max_fd;    
  
    int i;
    
    /* Create our socket for handling connections */
    listener = create_tcp_socket ( LISTEN_PORT );
    
    /* Zero out the master fd_set */
    FD_ZERO ( &master );
    
    /* Add the server socket to the set of sockets */
    FD_SET ( listener, &master );
    
    /* The highest file descriptor (fd) */
    max_fd = listener;
    
    /* Infinite loop */
    for ( ;; ) {
        
        /* Copy the master set into a temporary fd */
        readSet = master;
        
        /* Handle multiple connections via Select */
        if ( select ( max_fd + 1, &readSet, NULL, NULL, NULL ) == -1 ) {
            DIE ( "select() failed" );
            
        }
        
        /* Spin through all of the items in readSet and check for connections or requests */
        for ( i = 0; i <= max_fd; i++ ) {
            
            /* We've got a new one! */
            if (FD_ISSET ( i, &readSet ) ) {
                if ( i == listener ) {
                
                    /* Accept a new client */
                    new_fd = accept_tcp_connection ( listener );
                    
                    
                    /* Add it to the list of sockets */
                    FD_SET ( new_fd, &master );
                
                    /* Specify the new max, if need be */
                    if ( new_fd > max_fd ) {
                        max_fd = new_fd;
                    }
                    
                } else {
                    
                    /* Process information coming from a given socket, and close if necessary */
                    if ( handle_tcp_connection ( i, callback ) == 0 ) {
                        close ( i );
                        FD_CLR ( i, &master );
                    }
                    
                }
            }
        }
    }
    
    /* shut down */
    close ( listener );

    
}
Пример #25
0
void get_config_from_midware(const char *host, const char *page, char *buf, size_t len) {
  if (host == NULL || page == NULL) {
    perror("Could not connect");
    exit(1);
  }

  int sock = create_tcp_socket();
  char ip[16] = {0};
  get_ip(host, ip, sizeof(ip)-1);
  fprintf(stdout, "IP is %s\n", ip);

  struct sockaddr_in remote;
  remote.sin_family = AF_INET;
  int tmpres = inet_pton(AF_INET, ip, (void*)(&(remote.sin_addr.s_addr)));
  if (tmpres < 0) {
    perror("Can't set remote->sin_addr.s_addr");
    exit(1);
  } else if (tmpres == 0) {
    fprintf(stderr, "%s is not a valid IP address\n", ip);
    exit(1);
  }
  remote.sin_port = htons(80);	// http_port
  if (connect(sock, (const struct sockaddr*)&remote, sizeof(struct sockaddr)) < 0) {
    perror("Could not connect");
    exit(1);
  }

  char get_query[BUFSIZ] = {0};		// should be enough
  build_get_query(host, page, get_query, sizeof(get_query));
  fprintf(stderr, "Query <<START>>\n%sQuery <<END>>\n", get_query);

  int sent = 0;			// send the query to the server
  while (sent < strlen(get_query)) {
    tmpres = send(sock, get_query+sent, strlen(get_query)-sent, 0);
    if (tmpres == -1){
      perror("Can't send query");
      exit(1);
    }
    sent += tmpres;
  }

  int htmlstart = 0;
  char *htmlcontent, ret[BUFSIZ] = {0};
  while ((tmpres = recv(sock, ret, BUFSIZ, 0)) > 0) {
    if (htmlstart == 0) {
      /* Under certain conditions this will not work.
       * If the \r\n\r\n part is splitted into two messages
       * it will fail to detect the beginning of HTML content
       */
      htmlcontent = strstr(ret, "\r\n\r\n");
      if (htmlcontent != NULL){
	htmlstart = 1;
	htmlcontent += 4;
      }
    } else {
      htmlcontent = ret;
    }
    if (htmlstart) {
      printf("one more buf\n");
      fprintf(stdout, htmlcontent); // output
      strncpy(buf, htmlcontent, tmpres);
    }

    memset(ret, 0, tmpres);
  }
  if (tmpres < 0) {
    perror("Error receiving data");
  }

  close(sock);
}
Пример #26
0
char* http_get(char *host, int port, char *page) {
	struct sockaddr_in *remote;
	int sock;
	int tmpres;
	char *ip;
	char *get;
	char buf[BUFSIZ + 1];

	sock = create_tcp_socket();
	ip = get_ip(host);
	fprintf(stderr, "IP is %s\n", ip);
	remote = (struct sockaddr_in *) malloc(sizeof(struct sockaddr_in *));
	remote->sin_family = AF_INET;
	tmpres = inet_pton(AF_INET, ip, (void *) (&(remote->sin_addr.s_addr)));
	if (tmpres < 0) {
		perror("Can't set remote->sin_addr.s_addr");
		exit(1);
	} else if (tmpres == 0) {
		fprintf(stderr, "%s is not a valid IP address\n", ip);
		exit(1);
	}
	remote->sin_port = htons(port);

	if (connect(sock, (struct sockaddr *) remote, sizeof(struct sockaddr)) < 0) {
		perror("Could not connect");
		exit(1);
	}
	get = build_get_query(host, page);
	fprintf(stderr, "Query is:\n<<START>>\n%s<<END>>\n", get);

	//Send the query to the server
	int sent = 0;
	while (sent < strlen(get)) {
		tmpres = send(sock, get + sent, strlen(get) - sent, 0);
		if (tmpres == -1) {
			perror("Can't send query");
			exit(1);
		}
		sent += tmpres;
	}
	//now it is time to receive the page
	memset(buf, 0, sizeof(buf));
	int htmlstart = 0;
	char * htmlcontent;
	while ((tmpres = recv(sock, buf, BUFSIZ, 0)) > 0) {
		if (htmlstart == 0) {
			/* Under certain conditions this will not work.
			 * If the \r\n\r\n part is splitted into two messages
			 * it will fail to detect the beginning of HTML content
			 */
			htmlcontent = strstr(buf, "\r\n\r\n");
			if (htmlcontent != NULL) {
				htmlstart = 1;
				htmlcontent += 4;
			}
		} else {
			htmlcontent = buf;
		}
		if (htmlstart) {
			fprintf(stdout, htmlcontent);
		}

		memset(buf, 0, tmpres);
	}
	if (tmpres < 0) {
		perror("Error receiving data");
	}
	free(get);
	free(remote);
	free(ip);
	close(sock);

	return htmlcontent;
}
Пример #27
0
/*------------------------------------------------------------------------
 * MAIN PROGRAM
 *------------------------------------------------------------------------*/
int main(int argc, char *argv[])
{
    int                server_fd, client_fd;
    struct sockaddr_in remote_address;
    socklen_t          remote_length = sizeof(struct sockaddr_in);
    ttp_parameter_t    parameter;
    ttp_session_t      session;
    pid_t              child_pid;

    /* initialize our parameters */
    memset(&session, 0, sizeof(session));
    reset_server(&parameter);

    /* process our command-line options */
    process_options(argc, argv, &parameter);

    /* obtain our server socket */
    server_fd = create_tcp_socket(&parameter);
    if (server_fd < 0) {
        sprintf(g_error, "Could not create server socket on port %d", parameter.tcp_port);
        return error(g_error);
    }

    /* install a signal handler for our children */
    signal(SIGCHLD, reap);

    /* now show version / build information */
    #ifdef VSIB_REALTIME
    fprintf(stderr, "Tsunami Realtime Server for protocol rev %X\nRevision: %s\nCompiled: %s %s\n"
                    "   /dev/vsib VSIB accesses mode=%d, sample skip=%d, gigabit=%d, 1pps embed=%d\n"
                    "Waiting for clients to connect.\n",
            PROTOCOL_REVISION, TSUNAMI_CVS_BUILDNR, __DATE__ , __TIME__,
            vsib_mode, vsib_mode_skip_samples, vsib_mode_gigabit, vsib_mode_embed_1pps_markers);
    #else
    fprintf(stderr, "Tsunami Server for protocol rev %X\nRevision: %s\nCompiled: %s %s\n"
                    "Waiting for clients to connect.\n",
            PROTOCOL_REVISION, TSUNAMI_CVS_BUILDNR, __DATE__ , __TIME__);
    #endif

    /* while our little world keeps turning */
    while (1) {

        /* accept a new client connection */
        client_fd = accept(server_fd, (struct sockaddr *) &remote_address, &remote_length);
        if (client_fd < 0) {
            warn("Could not accept client connection");
            continue;
        } else {
            fprintf(stderr, "New client connecting from %s...\n", inet_ntoa(remote_address.sin_addr));
        }

        /* and fork a new child process to handle it */
        child_pid = fork();
        if (child_pid < 0) {
            warn("Could not create child process");
            continue;
        }
        session.session_id++;

        /* if we're the child */
        if (child_pid == 0) {

            /* close the server socket */
            close(server_fd);

            /* set up the session structure */
            session.client_fd = client_fd;
            session.parameter = &parameter;
            memset(&session.transfer, 0, sizeof(session.transfer));
            session.transfer.ipd_current = 0.0;

            /* and run the client handler */
            client_handler(&session);
            return 0;

        /* if we're the parent */
        } else {

            /* close the client socket */
            close(client_fd);
        }
    }
}