コード例 #1
0
ファイル: lispd_sockets.c プロジェクト: teto/lispmob32
int open_control_input_socket(int afi){

    const int   on      = 1;
    int         sock    = 0;

    sock = open_udp_socket(afi);

    sock = bind_socket(sock,afi,LISP_CONTROL_PORT);

    if(sock == BAD){
        return (BAD);
    }

    switch (afi){
        case AF_INET:

            /* IP_PKTINFO is requiered to get later the IPv4 destination address of incoming control packets*/
            if(setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &on, sizeof(on))< 0){
                LISPD_LOG(LISP_LOG_WARNING, "setsockopt IP_PKTINFO: %s", strerror(errno));
            }

        break;

        case AF_INET6:

            /* IPV6_RECVPKTINFO is requiered to get later the IPv6 destination address of incoming control packets*/
            if(setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on)) < 0){
                LISPD_LOG(LISP_LOG_WARNING, "setsockopt IPV6_RECVPKTINFO: %s", strerror(errno));
            }

        break;

        default:
            return(BAD);
    }
    return(sock);
}
コード例 #2
0
// return type
static int
ctrl_cmd(struct socket_server *ss, struct socket_message *result) {
	int fd = ss->recvctrl_fd;
	// the length of message is one byte, so 256+8 buffer size is enough.
	uint8_t buffer[256];
	uint8_t header[2];
	block_readpipe(fd, header, sizeof(header));
	int type = header[0];
	int len = header[1];
	block_readpipe(fd, buffer, len);
	// ctrl command only exist in local fd, so don't worry about endian.
	switch (type) {
	case 'S':
		return start_socket(ss,(struct request_start *)buffer, result);
	case 'B':
		return bind_socket(ss,(struct request_bind *)buffer, result);
	case 'L':
		return listen_socket(ss,(struct request_listen *)buffer, result);
	case 'K':
		return close_socket(ss,(struct request_close *)buffer, result);
	case 'O':
		return open_socket(ss, (struct request_open *)buffer, result, false);
	case 'X':
		result->opaque = 0;
		result->id = 0;
		result->ud = 0;
		result->data = NULL;
		return SOCKET_EXIT;
	case 'D':
		return send_socket(ss, (struct request_send *)buffer, result);
	default:
		fprintf(stderr, "socket-server: Unknown ctrl %c.\n",type);
		return -1;
	};

	return -1;
}
コード例 #3
0
int main(int argc, char **argv)
{
    if (argc < 4) {
        printf("\n\tUsage: %s <host> <port> <tcp|udp>\n\n", argv[0]);
        return 0;
    }

    set_sig_handler(SIGINT, int_handler);
    set_sig_handler(SIGURG, urg_handler);

    char *host = argv[1];
    char *port = argv[2];
    char *protocol = argv[3];

    int server_socket = create_socket(protocol);

    if (server_socket == -1) {
        perror("create_socket() error");
        return 0;
    }

    if (bind_socket(server_socket, host, atoi(port)) == -1) {
        perror("bind_socket() error");
        close(server_socket);
        return 0;
    }

    bool is_tcp = !strcmp(protocol, "tcp");

    if (is_tcp)
        TcpServer(server_socket);
    else
        UdpServer(server_socket);

    close(server_socket);
    return 0;
}
コード例 #4
0
ServerSocket::ServerSocket(int port, int host)
{
    int creation_exit = create_socket(AF_INET, SOCK_STREAM, 0);

    if(creation_exit < 0){
       std::cout << "Creation of socket failed: " << creation_exit << "\n" << std::endl;
       exit(1);
    } else{
       std::cout << "Creation exit arg: " << creation_exit << "\n" << std::endl;
    };

    prepare_host_address(AF_INET, host, port);
    std::cout << serv_addr.sin_family << " " << serv_addr.sin_addr.s_addr << " " << serv_addr.sin_port << "\n";

    struct sockaddr * temp = (struct sockaddr*)&serv_addr; //casting on pointers
    int binding_exit = bind_socket(listenfd, temp, sizeof(serv_addr));

    if(binding_exit < 0){
       std::cout << "Binding of socket failed: " << binding_exit << "\n" << std::endl;
       exit(1);
    } else{
       std::cout << "Binding exit arg: " << creation_exit << "\n" << std::endl;
    };
};
コード例 #5
0
int main() {
    int fd = -1;
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);

    int cfd = -1;
    struct sockaddr_in caddr;
    socklen_t  clen = sizeof(caddr);

    init_addr(&addr, AF_INET, 8888, "127.0.0.1");

    if ( (fd = create_socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("error: %s\n", strerror(errno));
        return -1;
    }

    set_nonblock(fd);
    set_reuseAddr(fd);

    if ( bind_socket(fd, (struct sockaddr*)&addr, len) < 0) {
        printf("error: %s\n", strerror(errno));
        return -1;
    }

    if (listen(fd, 10) != 0) {
        printf("error: %s\n", strerror(errno));
        return -1;
    }

    cfd = accept(fd, (struct sockaddr*)&caddr, &clen);
    if (cfd < 0) {
        printf("-- error: %s : %s\n", get_errnoStr(errno), strerror(errno));
    }

    return 0;
}
コード例 #6
0
void start_server(int port)
{
    signal(SIGCHLD,sigchld_handler);

    int client_length,socket_fd;
    struct sockaddr_in server_address,client_address;
    char *buf;
    ssize_t nbytes;

    socket_fd=create_socket();
    fill_address(&server_address,port,NULL);
    bind_socket(&server_address,socket_fd);

    printf("Server listening on port %i \n",ntohs(server_address.sin_port));

    while(1)
    {
        buf=(char *)malloc(sizeof(request));
        memset(buf,0,sizeof(request));
        client_length=sizeof(client_address);

        nbytes=recvfrom(socket_fd,buf,BUFFLEN,0,(struct sockaddr *)&client_address,&client_length);
        if(nbytes<0)
            err("Error in receiving request from client\n");
//        receive_message(socket_fd,buf,&client_address);

        fprintf(stderr,"\n\nReceived packet from client %s:%d\n",inet_ntoa(client_address.sin_addr), ntohs(client_address.sin_port));
        fflush(stdin);
        request *client_req=(request *)malloc(sizeof(request));
        decompress(client_req,buf);

        create_child(socket_fd,(struct sockaddr *)&client_address, client_req);
    }

    close(socket_fd);
}
コード例 #7
0
int
open_control_input_socket(int afi)
{

    const int on = 1;
    int sock = ERR_SOCKET;

    sock = open_udp_datagram_socket(afi);
    if (sock == ERR_SOCKET) {
        return (ERR_SOCKET);
    }
    bind_socket(sock, afi, NULL, LISP_CONTROL_PORT);



    switch (afi) {
    case AF_INET:
        /* IP_PKTINFO is requiered to get later the IPv4 destination address
         * of incoming control packets */
        if (setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &on, sizeof(on)) < 0) {
            LMLOG(LWRN, "setsockopt IP_PKTINFO: %s", strerror(errno));
        }
        break;
    case AF_INET6:
        /* IPV6_RECVPKTINFO is requiered to get later the IPv6 destination
         * address of incoming control packets */
        if (setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on))
                < 0) {
            LMLOG(LWRN, "setsockopt IPV6_RECVPKTINFO: %s", strerror(errno));
        }
        break;
    default:
        return (ERR_SOCKET);
    }
    return (sock);
}
コード例 #8
0
ファイル: test_socket.cpp プロジェクト: emwhbr/cplusplus
int main(void)
{
  long rc;

  ///////////////////////////////////////////////////
  //         Test of changing byte order
  ///////////////////////////////////////////////////
  uint64_t data64 = 0x0102030405060708;
  printf("u64 (host):0x%016lx\n", data64);
  print_bytes64(data64);

  data64 = hton64(data64);
  printf("u64 (net):0x%016lx\n", data64);
  print_bytes64(data64);

  data64 = ntoh64(data64);
  printf("u64 (host):0x%016lx\n", data64);
  print_bytes64(data64);

  printf("\n");

  data64 = 0xcafedeca01020304;
  printf("u64 (host):0x%016lx\n", data64);
  print_bytes64(data64);

  hton64(&data64);
  printf("u64 (net):0x%016lx\n", data64);
  print_bytes64(data64);

  ntoh64(&data64);
  printf("u64 (host):0x%016lx\n", data64);
  print_bytes64(data64);

  printf("\n");

  uint32_t data32 = 0xdeadbeef;
  printf("u32 (host):0x%08x\n", data32);
  print_bytes32(data32);

  hton32(&data32);
  printf("u32 (net):0x%08x\n", data32);
  print_bytes32(data32);

  ntoh32(&data32);
  printf("u32 (host):0x%08x\n", data32);
  print_bytes32(data32);

  printf("\n");

  ///////////////////////////////////////////////////
  //         Test of address transformation
  ///////////////////////////////////////////////////

  uint32_t net_addr;
  char ip_address[20];  

  to_net_address("192.168.100.17", &net_addr);
  printf("Net-address (classic)  : 0x%08x\n", net_addr);

  to_net_address(ANY_IP_ADDRESS, &net_addr);
  printf("Net-address (any)      : 0x%08x\n", net_addr);

  to_net_address(LOOPBACK_IP_ADDRESS, &net_addr);
  printf("Net-address (loopback) : 0x%08x\n", net_addr);

  to_net_address(BROADCAST_IP_ADDRESS, &net_addr);
  printf("Net-address (broadcast): 0x%08x\n", net_addr);

  net_addr = 0xc0a86411; // 192.168.100.17
  to_ip_address(net_addr, ip_address, 20);
  printf("IP-address (classic)  : %s\n", ip_address);

  net_addr = 0x0; // 0.0.0.0
  to_ip_address(net_addr, ip_address, 20);
  printf("IP-address (any)      : %s\n", ip_address);

  net_addr = 0x7f000001; // 127.0.0.1
  to_ip_address(net_addr, ip_address, 20);
  printf("IP-address (loopback) : %s\n", ip_address);

  net_addr = 0xffffffff; // 255.255.255.255
  to_ip_address(net_addr, ip_address, 20);
  printf("IP-address (broadcast): %s\n", ip_address);

  printf("\n");

  ///////////////////////////////////////////////////
  //         Test of resolving hostname
  ///////////////////////////////////////////////////

  resolve_element resolve_list[10];
  unsigned actual;

  bzero(resolve_list, sizeof(resolve_list));
  rc = resolve_hostname("www.google.com", 80, resolve_list, 10, &actual);
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    printf("*** ERROR (resolve_hostname)");
    return 1;
  }
  for (unsigned i=0; i < actual; i++) {
    to_ip_address(resolve_list[i].net_addr, ip_address, 20);
    printf("Net-addr=0x%08x (%s),\tprotocol=%04d, socktype=%04d\n",
	   resolve_list[i].net_addr,
	   ip_address,
	   resolve_list[i].protocol,
	   resolve_list[i].socktype);
  }

  printf("\n");

  ///////////////////////////////////////////////////
  //         Test of connected UDP socket
  ///////////////////////////////////////////////////

  int udp_socket;
  socket_address udp_local_sa;
  socket_address udp_dest_sa;

  rc = create_udp_socket(&udp_socket);
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    printf("*** ERROR (create_udp_socket)");
    return 1;
  }

  to_net_address(ANY_IP_ADDRESS, &udp_local_sa.net_addr);
  udp_local_sa.port = 14000;

  rc = bind_socket(udp_socket, udp_local_sa);
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    printf("*** ERROR (bind_socket)");
    return 1;
  }

  to_net_address("192.168.0.1", &udp_dest_sa.net_addr);
  udp_dest_sa.port = 25000;

  rc = connect_socket(udp_socket, udp_dest_sa);
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    printf("*** ERROR (connect_socket)");
    return 1;
  }

  bzero(&udp_local_sa, sizeof(udp_local_sa));
  bzero(&udp_dest_sa, sizeof(udp_dest_sa));

  get_socket_local_address(udp_socket, &udp_local_sa);
  get_socket_peer_address(udp_socket, &udp_dest_sa);

  to_ip_address(udp_local_sa.net_addr, ip_address, 20);
  printf("(UDP) Local IP : %s, port = %d\n", ip_address, udp_local_sa.port);

  to_ip_address(udp_dest_sa.net_addr, ip_address, 20);
  printf("(UDP) Dest IP  : %s, port = %d\n", ip_address, udp_dest_sa.port);

  rc = close_socket(udp_socket);
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    printf("*** ERROR (close_socket)");
    return 1;
  }

  return 0;
}
コード例 #9
0
ファイル: main.c プロジェクト: caioafreitas/CursoC2015.2
int main(int argc, char *argv[])
{
    SOCKET sockfd = create_socket();

    if (sockfd != INVALID_SOCKET)
    {
        if (bind_socket(&sockfd, PORT_NO, 10))
        {
            SOCKET sockets[MAX_SOCKETS] = {INVALID_SOCKET};
            int opened_sockets = 0;

            while (1)
            {
                int idx, max;
				
                if (opened_sockets < MAX_SOCKETS)
                {
                    SOCKET new_sockfd = wait_connection(&sockfd);

                    if (new_sockfd != INVALID_SOCKET)
                    {
                        sockets[opened_sockets++] = new_sockfd;
                    }
                    else if (WSAGetLastError() != WSAETIMEDOUT)
                    {
                        //printf("ERROR waiting\n");
                    }
                }

                for (idx = 0, max = opened_sockets; idx < max; idx++)
                {
                    if (sockets[idx] != INVALID_SOCKET)
                    {
                        if (do_processing(&sockets[idx]) < 0)
                        {
							printf("Disconnecting...\n");
							disconnect_socket(&sockets[idx]);
							sockets[idx] = sockets[opened_sockets-1];
							sockets[opened_sockets-1] = INVALID_SOCKET;
							opened_sockets--;
                        }
                    }
                }
            }
        }
        else
        {
            perror("ERROR binding");
        }

        disconnect_socket(&sockfd);
    }
    else
    {
        perror("ERROR opening socket");
    }

    destroy_socket(&sockfd);

    return 0;
}
コード例 #10
0
ファイル: sock.c プロジェクト: hilbix/tinyproxy
/*
 * Open a connection to a remote host.  It's been re-written to use
 * the getaddrinfo() library function, which allows for a protocol
 * independent implementation (mostly for IPv4 and IPv6 addresses.)
 */
int opensock_acl (const char *host, int port, const char *bind_to, vector_t acl)
{
        int sockfd, n;
        struct addrinfo hints, *res, *ressave;
        char portstr[6];

        assert (host != NULL);
        assert (port > 0);

        memset (&hints, 0, sizeof (struct addrinfo));
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;

        snprintf (portstr, sizeof (portstr), "%d", port);

        n = getaddrinfo (host, portstr, &hints, &res);
        if (n != 0) {
                log_message (LOG_ERR,
                             "opensock: Could not retrieve info for %s", host);
                return -1;
        }

        ressave = res;
	sockfd = -1; /* keep lint happy */
        do {
		char ipaddr[IP_LENGTH];
		if (get_ip_string (res->ai_addr, ipaddr, IP_LENGTH) == NULL)
			continue;
		/* For optimizing this check_acl must be splitted
		 * into host checking and ip checking siblings
		 */
		if (! check_acl_quiet(ipaddr, host, acl)) {
			log_message(LOG_NOTICE, "Denied destination '%s' [%s]", host, ipaddr);
			continue;	/* try next address	*/
		}
		log_message(LOG_CONN, "Allowed destination '%s' [%s]", host, ipaddr);

                sockfd =
                    socket (res->ai_family, res->ai_socktype, res->ai_protocol);
                if (sockfd < 0)
                        continue;       /* ignore this one */

                /* Bind to the specified address */
                if (bind_to) {
                        if (bind_socket (sockfd, bind_to,
                                         res->ai_family) < 0) {
                                close (sockfd);
                                continue;       /* can't bind, so try again */
                        }
                } else if (config.bind_address) {
                        if (bind_socket (sockfd, config.bind_address,
                                         res->ai_family) < 0) {
                                close (sockfd);
                                continue;       /* can't bind, so try again */
                        }
                }

                if (connect (sockfd, res->ai_addr, res->ai_addrlen) == 0)
                        break;  /* success */

                close (sockfd);
        } while ((res = res->ai_next) != NULL);

        freeaddrinfo (ressave);
        if (res == NULL) {
                log_message (LOG_ERR,
                             "opensock: Could not establish a connection to %s",
                             host);
                return -1;
        }

        return sockfd;
}
コード例 #11
0
ファイル: lispd_iface_mgmt.c プロジェクト: Alphalink/lispmob
void process_nl_new_link (struct nlmsghdr *nlh)
{
    struct ifinfomsg                    *ifi            = NULL;
    lispd_iface_elt                     *iface          = NULL;
    int                                 iface_index     = 0;
    uint8_t                             status          = UP;
    char                                iface_name[IF_NAMESIZE];
    uint32_t                            old_iface_index = 0;

    ifi = (struct ifinfomsg *) NLMSG_DATA (nlh);
    iface_index = ifi->ifi_index;


    iface = get_interface_from_index(iface_index);

    if (iface == NULL){
        /*
         * In some OS when a virtual interface is removed and added again, the index of the interface change.
         * Search lispd_iface_elt by the interface name and update the index.
         */
        if (if_indextoname(iface_index, iface_name) != NULL){
            iface = get_interface(iface_name);
        }
        if (iface == NULL){
            lispd_log_msg(LISP_LOG_DEBUG_2, "process_nl_new_link: the netlink message is not for any interface associated with RLOCs  (%s)",
                    iface_name);
            return;
        }else{
            old_iface_index = iface->iface_index;
            iface->iface_index = iface_index;
#ifndef VPNAPI
            lispd_log_msg(LISP_LOG_DEBUG_2,"process_nl_new_link: The new index of the interface %s is: %d. Updating tables",
                    iface_name, iface->iface_index);
            /* Update routing tables and reopen sockets*/
            if (iface->ipv4_address->afi != AF_UNSPEC){
                del_rule(AF_INET,0,old_iface_index,old_iface_index,RTN_UNICAST,iface->ipv4_address,32,NULL,0,0);
                add_rule(AF_INET,0,iface_index,iface_index,RTN_UNICAST,iface->ipv4_address,32,NULL,0,0);
                close(iface->out_socket_v4);
                iface->out_socket_v4 = new_device_binded_raw_socket(iface->iface_name,AF_INET);
                bind_socket(iface->out_socket_v4,AF_INET,iface->ipv4_address,0);
            }
            if (iface->ipv6_address->afi != AF_UNSPEC){
                del_rule(AF_INET6,0,old_iface_index,old_iface_index,RTN_UNICAST,iface->ipv6_address,128,NULL,0,0);
                add_rule(AF_INET6,0,iface_index,iface_index,RTN_UNICAST,iface->ipv6_address,128,NULL,0,0);
                close(iface->out_socket_v6);
                iface->out_socket_v6 = new_device_binded_raw_socket(iface->iface_name,AF_INET6);
                bind_socket(iface->out_socket_v6,AF_INET6,iface->ipv6_address,0);
            }
#endif
        }
    }

    // We relaxed condition to be UP from IFF_RUNNING to only IFF_UP
    if ((ifi->ifi_flags & IFF_UP) != 0){
        lispd_log_msg(LISP_LOG_DEBUG_1, "process_nl_new_link: Interface %s changes its status to UP",iface->iface_name);
        status = UP;
    }
    else{
        lispd_log_msg(LISP_LOG_DEBUG_1, "process_nl_new_link: Interface %s changes its status to DOWN",iface->iface_name);
        status = DOWN;
    }

    process_link_status_change (iface, status);
}
コード例 #12
0
ファイル: main.c プロジェクト: W-santos/CursoC2015.2
int main(int argc, char *argv[])
{
	WSADATA wsaData;
	  // Initialize Winsock
    int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
        printf("WSAStartup failed with error: %d\n", iResult);
        return 1;
    }
    SOCKET sockfd = create_socket();

    if (sockfd != INVALID_SOCKET)
    {
        if (bind_socket(&sockfd, PORT_NO, 10))
        {
            SOCKET sockets[MAX_SOCKETS] = {INVALID_SOCKET};
            int opened_sockets = 0;

            while (1)
            {
                int idx, max;
                if (opened_sockets < MAX_SOCKETS)
                {
                    SOCKET new_sockfd = wait_connection(&sockfd);

                    if (new_sockfd != INVALID_SOCKET)
                    {
                        sockets[opened_sockets++] = new_sockfd;
                    }
                    //else if (errno != WSAETIMEDOUT)
                    {
                        //puts("ERROR waiting");
                    }
                }

                for (idx = 0, max = opened_sockets; idx < max; idx++)
                {
                    if (sockets[idx] != INVALID_SOCKET)
                    {
                        if (do_processing(&sockets[idx])==-1)
                        {
                            if (errno != WSAETIMEDOUT)
                            {
                                printf("Disconnecting...\n");
                                disconnect_socket(&sockets[idx]);
                                sockets[idx] = sockets[opened_sockets-1];
                                sockets[opened_sockets-1] = INVALID_SOCKET;
                                opened_sockets--;
                            }
                        }
                    }
                }
            }
        }
        else
        {
            printf("ERROR binding\n");
        }

        disconnect_socket(&sockfd);
    }
    else
    {
        printf("ERROR opening socket\n");
    }

    destroy_socket(&sockfd);

    return 0;
}
コード例 #13
0
ファイル: udpspy.c プロジェクト: malaise/c
int main (const int argc, const char *argv[]) {
  /* Result of operation */
  int res;
  char buffer[255];

  /* The socket and its fd */
  soc_token socket = init_soc;
  int fd;

  /* Event result */
  boolean read;
  timeout_t timeout;
  int evtfd;

  /* parse arguments */
  parse_args (argc, argv);

  /* Create socket and get fd */
  if ( (res = soc_open (&socket, udp_socket)) != SOC_OK) {
    trace ("soc_open error", soc_error (res));
    error ("cannot open socket", "");
  }
  if ( (res = soc_get_id (socket, &fd)) != SOC_OK) {
    trace ("soc_get_id error", soc_error (res));
    error ("cannot get socket fd", "");
  }
  /* Bind socket to lan:port */
  bind_socket (socket);

  /* Attach fd for reading */
  if ( (res = evt_add_fd (fd, TRUE)) != WAIT_OK) {
    trace ("evt_add_fd error", "");
    error ("cannot add fd", "");
  }

  /* Main loop */
  timeout.tv_sec = -1;
  timeout.tv_usec = -1;
  for (;;) {
    /* Infinite wait for events */
    if ( (res = evt_wait (&evtfd, & read, &timeout)) != WAIT_OK) {
      trace ("evt_wait error", "");
      error ("cannot wait for event", "");
    }
    /* Analyse event */
    if (evtfd == SIG_EVENT) {
      if (get_signal() == SIG_TERMINATE) {
        /* Sigterm/sigint */
        break;
      } /* else unexpected signal => drop */
    } else if (evtfd == fd) {
      /* Got a packet: read it */
      res = soc_receive (socket, message, sizeof(message), TRUE);
      if (res < 0) {
        sprintf (buffer, "%d", res);
        trace ("soc_receive error", soc_error (res));
        error ("cannot read message", soc_error(res));
      } else {
        if (res > (int)sizeof(message)) {
          sprintf (buffer, "%d", res);
          trace ("soc_receive truncated message length", "buffer");
          res = (int)sizeof(message);
         }
         /* Put message info */
         display (socket, message, res);
      }
    } else if (evtfd >= 0) {
      /* Unexpected event on an unexpected fd */
      sprintf (buffer, "%d", evtfd);
      trace ("evt_wait got unexpected even on fd", "buffer");
      error ("even on unexpected fd", "");
    }

  } /* Main loop */

  /* Done */
  (void) evt_del_fd (fd, TRUE);
  (void) soc_close (&socket);
  the_end ();
}
コード例 #14
0
ファイル: main.c プロジェクト: FloooD/custom_cs2dsrv
int main(int argc, char *argv[]){
	init_parse();

	// Parses the commandline arguments
	parse_opts(argc, argv); // IE: ./server -cserver.cfg --name "My Server"

	// server config
	ReadServerCfg(cfg_file ? :"server.cfg");

	// init sockets
	struct sockaddr_in newclient;
	unsigned char buffer[MAX_BUF];
	int size;
	fd_set descriptor; //I don't know
	sock = create_socket();
	bind_socket(&sock, INADDR_ANY, sv_hostport);

	// on termination
	atexit(&cleanup);
	signal(SIGABRT, &exit);
	signal(SIGTERM, &exit);
	signal(SIGINT, &exit);

	// initialize rest of stuff
	OnServerStart();

#ifndef _WIN32
	// fps control
	const int inc = NS_PER_S / sv_fps;
	int frame = 0;
	int previous = 0;

	struct timespec current, next;
	clock_gettime(CLOCK_MONOTONIC, &next);
#endif

	// timeval for select
	struct timeval timeout;
	timeout.tv_sec = 0;
	timeout.tv_usec = 0;

	//main loop
	while (1) {
#ifndef _WIN32
		frame++;
		next.tv_nsec += inc;
		while (next.tv_nsec > NS_PER_S) { //happens exactly once a second
			next.tv_nsec -= NS_PER_S;
			next.tv_sec++;

			fpsnow = frame - previous;
			previous = frame;
			OnSecond();
		}
#endif
		OnFrame();

		FD_ZERO(&descriptor);
		FD_SET(sock, &descriptor);
		select(sock + 1, &descriptor, NULL, NULL, &timeout);

		if (FD_ISSET(sock, &descriptor)){
			size = udp_receive(sock, buffer, MAX_BUF, &newclient);

			if (size < 3) {
				perror("Invalid packet! (size < 3)\n");
			} else {
				stream *packet = init_stream(NULL);
				Stream.write(packet, buffer+2, size-2);

				// There's a chance that the guy left before all of the packet has been processed.
				while(1){
					int id = IsPlayerKnown(newclient.sin_addr, newclient.sin_port);
					if (id){
						if (ValidatePacket(buffer,id)){
							PacketConfirmation(buffer,id); //If the numbering is even, send a confirmation
							player[id].lastpacket = mtime();
							int pid = Stream.read_byte(packet);
							known_handler h = known_table[pid];
							if (!h){
								printf("Unhandled packet originating from %s (id:%d)\n", player[id].name, id);
								//stream *lolbuf = init_stream(NULL);
								//Stream.write(lolbuf, buffer, size);
								//unknown(lolbuf, pid);
								unknown(packet, pid);
							} else
								h(packet, id);
						}
					}else{
						int pid = Stream.read_byte(packet);
						unknown_handler h = unknown_table[pid];
						if (!h)
							unknown(packet, pid);
						else
							h(packet, &newclient);
					}

					if (EMPTY_STREAM(packet)){
						free(packet);
						break;
					}
				}
			}
		}

		check_sendqueue();

#ifdef _WIN32
		Sleep(1000 / sv_fps); //who cares about windows :D
#else
		clock_gettime(CLOCK_MONOTONIC, &current);
		if (((current.tv_sec == next.tv_sec) && (current.tv_nsec < next.tv_nsec)) || (current.tv_sec < next.tv_sec)) {
			clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL);
		} else {
			next.tv_nsec = current.tv_nsec + (current.tv_sec - next.tv_sec) * NS_PER_S;
		}
#endif
	}
	return EXIT_SUCCESS;
}
コード例 #15
0
ファイル: listener.c プロジェクト: extremeshok/sniproxy
static int
init_listener(struct Listener *listener, const struct Table_head *tables, struct ev_loop *loop) {
    struct Table *table = table_lookup(tables, listener->table_name);
    if (table == NULL) {
        err("Table \"%s\" not defined", listener->table_name);
        return -1;
    }
    init_table(table);
    listener->table = table_ref_get(table);

    /* If no port was specified on the fallback address, inherit the address
     * from the listening address */
    if (listener->fallback_address &&
            address_port(listener->fallback_address) == 0)
        address_set_port(listener->fallback_address,
                address_port(listener->address));

    int sockfd = socket(address_sa(listener->address)->sa_family, SOCK_STREAM, 0);
    if (sockfd < 0) {
        err("socket failed: %s", strerror(errno));
        return -2;
    }

    /* set SO_REUSEADDR on server socket to facilitate restart */
    int on = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    int result = bind(sockfd, address_sa(listener->address),
            address_sa_len(listener->address));
    if (result < 0 && errno == EACCES) {
        /* Retry using binder module */
        close(sockfd);
        sockfd = bind_socket(address_sa(listener->address),
                address_sa_len(listener->address));
        if (sockfd < 0) {
            char address[128];
            err("binder failed to bind to %s",
                display_address(listener->address, address, sizeof(address)));
            close(sockfd);
            return -3;
        }
    } else if (result < 0) {
        char address[128];
        err("bind %s failed: %s",
            display_address(listener->address, address, sizeof(address)),
            strerror(errno));
        close(sockfd);
        return -3;
    }

    if (listen(sockfd, SOMAXCONN) < 0) {
        err("listen failed: %s", strerror(errno));
        close(sockfd);
        return -4;
    }


    int flags = fcntl(sockfd, F_GETFL, 0);
    fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);

    listener_ref_get(listener);
    ev_io_init(&listener->watcher, accept_cb, sockfd, EV_READ);
    listener->watcher.data = listener;
    listener->backoff_timer.data = listener;

    ev_io_start(loop, &listener->watcher);

    return sockfd;
}
コード例 #16
0
ファイル: q_nwif.c プロジェクト: S73417H/opensplice
int make_socket
(
  os_socket * sock,
  unsigned short port,
  c_bool stream,
  c_bool reuse,
  const os_sockaddr_storage * mcip,
  const char * address
)
{
  int rc = -2;

  *sock = os_sockNew ((config.useIpv6 ? AF_INET6 : AF_INET), stream ? SOCK_STREAM : SOCK_DGRAM);

  if (! Q_VALID_SOCKET (*sock))
  {
    print_sockerror ("socket");
    return rc;
  }

  if (port && reuse && ((rc = set_reuse_options (*sock)) < 0))
  {
    goto fail;
  }

  if
  (
    (rc = set_rcvbuf (*sock) < 0) ||
    (rc = set_sndbuf (*sock) < 0) ||
    ((rc = maybe_set_dont_route (*sock)) < 0) ||
    ((rc = bind_socket (*sock, port, address)) < 0)
  )
  {
    goto fail;
  }

  if (! stream)
  {
    if ((rc = set_mc_options_transmit (*sock)) < 0)
    {
      goto fail;
    }
  }

  if (stream)
  {
#ifdef SO_NOSIGPIPE
    set_socket_nosigpipe (*sock);
#endif
#ifdef TCP_NODELAY
    if (config.tcp_nodelay)
    {
      set_socket_nodelay (*sock);
    }
#endif
  }

  if (mcip && ((rc = join_mcgroups (*sock, mcip)) < 0))
  {
    goto fail;
  }

  return 0;

fail:

  os_sockFree (*sock);
  *sock = Q_INVALID_SOCKET;
  return rc;
}
コード例 #17
0
ファイル: httpproxy.c プロジェクト: khaynie/cpsc360
void http_proxy_start( unsigned int port, unsigned int cache_slots, unsigned int max_size ) {    
  int i = 0;
  int listenfd, connfd;

  // Set up SIGPIPE error handler
  signal(SIGPIPE, sighandler);

  pthread_t *pool = calloc(sizeof(pthread_t), POOL_SIZE);

  cache_list = calloc(sizeof(http_cache_t), cache_slots);

  // Allocate thread pool

  for( i=0; i < POOL_SIZE; i++) {
    int *tid = calloc(sizeof(int), 0);
    *tid = i;
    if (pthread_create(&(pool[i]), NULL, thread_pool_func, (void *)tid) != 0) {
      #ifdef DEBUG
      fprintf(stderr, "Could not create thread #%d.\n",i);
      #endif
      exit(-1);
    }
  }

  // Allocate cache pool
  for( i = 0; i < cache_slots; i++ ) {
    cache_list[i].host = NULL;
    cache_list[i].contents = NULL;
    cache_list[i].url = NULL;
    cache_list[i].next = NULL;
    cache_list[i].prev = NULL;
    cache_list[i].exists = -1;
  }
  
  // Initialize cache pool
  cache_head = &cache_list[0];
  cache_tail = &cache_list[cache_slots - 1];
  for( i = 0; i < cache_slots; i++ ) {
    if( i > 0 )
      cache_list[i].prev = &cache_list[i-1];
    if( i < cache_slots - 1 )  
      cache_list[i].next = &cache_list[i+1];
  }
  
  // Bind socket for server
  if((listenfd = bind_socket( port, 1 )) < 0 ) {
    #ifdef DEBUG
    fprintf(stderr, "ERROR\tError creating socket.\n");
    #endif
    exit(1);
  }

  // Listen for connections on socket, 1024 max connections
	if ((listen(listenfd, 1024)) < 0) {
    #ifdef DEBUG
		fprintf(stderr, "ERROR\tError listening on socket.\n");
    #endif
		exit(1);
  }
  
  // Begin accept loop -- catch all incoming connections
	while( 1 ) {
	  #ifdef DEBUG
	  fprintf(stderr, "Waiting for a connection...\n");
	  #endif
	  
	  // Connection grabbed, attempting to accept!
	  if((connfd = accept(listenfd, (struct sockaddr *) NULL, NULL)) < 0) {
      #ifdef DEBUG
	    fprintf(stderr, "ERROR\tError accepting connection.\n");
      #endif
	  } else {
	    #ifdef DEBUG
	    fprintf(stderr, "Accepted connection, enqueueing.\n\n");
	    #endif
	    // Successful, handle it 
	    enqueue_connection( connfd );
	  }
	}
}
コード例 #18
0
ファイル: bind.c プロジェクト: ToThePradoHotel/libssh
int ssh_bind_listen(ssh_bind sshbind) {
  const char *host;
  socket_t fd;

  sshbind->dsa = NULL;
  sshbind->rsa = NULL;

  if (ssh_init() < 0) {
    ssh_set_error(sshbind, SSH_FATAL, "ssh_init() failed");
    return -1;
  }

  if (sshbind->dsakey) {
    if (sshbind->dsakey == NULL && sshbind->rsakey == NULL) {
      ssh_set_error(sshbind, SSH_FATAL,
        "DSA or RSA host key file must be set before listen()");
      return SSH_ERROR;
    }
    sshbind->dsa = _privatekey_from_file(
      sshbind, sshbind->dsakey, SSH_KEYTYPE_DSS
    );
    if (sshbind->dsa == NULL) {
      return -1;
    }
  }

  if (sshbind->rsakey) {
    sshbind->rsa = _privatekey_from_file(
      sshbind, sshbind->rsakey, SSH_KEYTYPE_RSA
    );
    if (sshbind->rsa == NULL) {
      privatekey_free(sshbind->dsa);
      return -1;
    }
  }

  host = sshbind->bindaddr;
  if (host == NULL) {
    host = "0.0.0.0";
  }

  fd = bind_socket(sshbind, host, sshbind->bindport);
  if (fd == SSH_INVALID_SOCKET) {
    privatekey_free(sshbind->dsa);
    privatekey_free(sshbind->rsa);
    return -1;
  }
  sshbind->bindfd = fd;

  if (listen(fd, 10) < 0) {
    ssh_set_error(sshbind, SSH_FATAL,
        "Listening to socket %d: %s",
        fd, strerror(errno));
    close(fd);
    privatekey_free(sshbind->dsa);
    privatekey_free(sshbind->rsa);
    return -1;
  }

  return 0;
}
コード例 #19
0
ファイル: lispd_iface_mgmt.c プロジェクト: Alphalink/lispmob
void activate_interface_address(
        lispd_iface_elt     *iface,
        lisp_addr_t         new_address)
{
    lispd_iface_mappings_list       *mapping_list               = NULL;
    lispd_mapping_elt               *mapping                    = NULL;
    lispd_locators_list             **not_init_locators_list    = NULL;
    lispd_locators_list             **locators_list             = NULL;
    lispd_locator_elt               *locator                    = NULL;

#ifndef VPNAPI
    switch(new_address.afi){
    case AF_INET:
        iface->out_socket_v4 = new_device_binded_raw_socket(iface->iface_name,AF_INET);
        bind_socket(iface->out_socket_v4,AF_INET,&new_address,0);
        break;
    case AF_INET6:
        iface->out_socket_v6 = new_device_binded_raw_socket(iface->iface_name,AF_INET6);
        bind_socket(iface->out_socket_v6,AF_INET6,&new_address,0);
        break;
    }
#endif
    mapping_list = iface->head_mappings_list;
    /*
     * Activate the locator for each mapping associated with the interface
     */
    while (mapping_list != NULL){
        mapping = mapping_list->mapping;
        lispd_log_msg(LISP_LOG_DEBUG_2,"Activating locator %s associated to the EID %s/%d\n",
                get_char_from_lisp_addr_t(new_address),
                get_char_from_lisp_addr_t(mapping->eid_prefix),
                mapping->eid_prefix_length);
        not_init_locators_list = &(((lcl_mapping_extended_info *)mapping->extended_info)->head_not_init_locators_list);
        locator = extract_locator_from_list (not_init_locators_list, &new_address);
        if (locator != NULL){
            switch(new_address.afi){
            case AF_INET:
                mapping_list->use_ipv4_address = TRUE;
                locators_list = &mapping->head_v4_locators_list;
                break;
            case AF_INET6:
                mapping_list->use_ipv6_address = TRUE;
                locators_list = &mapping->head_v6_locators_list;
                break;
            }
            /* Add the activated locator */
            if (add_locator_to_list (locators_list,locator) == GOOD){
                mapping->locator_count = mapping->locator_count + 1;
            }else{
                free_locator(locator);
            }
        }else{
            lispd_log_msg(LISP_LOG_DEBUG_1,"activate_interface_address: No locator with address %s has been found"
                    " in the not init locators list of the mapping %s/%d. Is priority equal to -1 for this EID and afi?",
                    get_char_from_lisp_addr_t(new_address),
                    get_char_from_lisp_addr_t(mapping->eid_prefix),
                    mapping->eid_prefix_length);
        }
        mapping_list = mapping_list->next;
    }
}
コード例 #20
0
ファイル: sock.c プロジェクト: lianqiw/maos
/**
   Open a port and listen to it. Calls respond(sock) to handle data. If
   timeout_fun is not NULL, it will be called when 1) connection is
   establed/handled, 2) every timeout_sec if timeout_sec>0. This function only
   return at error.
   if localpath is not null and start with /, open the local unix port also
   if localpath is not null and contains ip address, only bind to that ip address
 */
void listen_port(uint16_t port, char *localpath, int (*responder)(int),
		 double timeout_sec, void (*timeout_fun)(), int nodelay){
    register_signal_handler(scheduler_signal_handler);

    fd_set read_fd_set;
    fd_set active_fd_set;
    FD_ZERO (&active_fd_set);
    char *ip=0;
    int sock_local=-1;
    if(localpath){
	if(localpath[0]=='/'){
	    //also bind to AF_UNIX
	    sock_local = bind_socket_local(localpath);
	    if(sock_local==-1){
		dbg("bind to %s failed\n", localpath);
	    }else{
		if(!listen(sock_local, 1)){
		    FD_SET(sock_local, &active_fd_set);
		}else{
		    perror("listen");
		    close(sock_local);
		sock_local=-1;
		}
	    }
	}else{
	    ip=localpath;
	}
    }

    int sock = bind_socket (ip, port);
    if(nodelay){//turn off tcp caching.
	socket_tcp_nodelay(sock);
    }
    if (listen (sock, 1) < 0){
	perror("listen");
	exit(EXIT_FAILURE);
    }

    FD_SET (sock, &active_fd_set);
 
    while(quit_listen!=2){
	if(quit_listen==1){
	    /*
	      shutdown(sock, SHUT_WR) sends a FIN to the peer, therefore
	      initialize a active close and the port will remain in TIME_WAIT state.

	      shutdown(sock, SHUT_RD) sends nother, just mark the scoket as not readable.

	      accept() create a new socket on the existing port. A socket is identified by client ip/port and server ip/port.
	      
	      It is the port that remain in TIME_WAIT state.
	     */
	    //shutdown(sock, SHUT_RDWR);
	    //shutdown(sock_local, SHUT_RDWR);
	    /*Notice existing client to shutdown*/
	    for(int i=0; i<FD_SETSIZE; i++){
		if(FD_ISSET(i, &active_fd_set) && i!=sock && i!=sock_local){
		    int cmd[3]={-1, 0, 0};
		    stwrite(i, cmd, 3*sizeof(int)); //We ask the client to actively close the connection
		    //shutdown(i, SHUT_WR);
		}
	    }
	    usleep(1e5);
	    quit_listen=2;
	    //don't break. Listen for connection close events.
	}
	if(timeout_fun){
	    timeout_fun();
	}

	struct timeval timeout;
	timeout.tv_sec=timeout_sec;
	timeout.tv_usec=(timeout_sec-timeout.tv_sec)*1e6;
	read_fd_set = active_fd_set;
	if(select(FD_SETSIZE, &read_fd_set, NULL, NULL, timeout_sec>0?&timeout:0)<0){
	    if(errno==EINTR){
		warning("select failed: %s\n", strerror(errno));
		continue;
	    }else if(errno==EBADF){
		warning("bad file descriptor: %s\n", strerror(errno));
		break;//bad file descriptor
	    }else{
		warning("unknown error: %s\n", strerror(errno));
		break;
	    }
	}
	for(int i=0; i<FD_SETSIZE; i++){
	    if(FD_ISSET(i, &read_fd_set)){
		if(i==sock){
		    /* Connection request on original socket. */
		    socklen_t size=sizeof(struct sockaddr_in);
		    struct sockaddr_in clientname;
    		    int port2=accept(i, (struct sockaddr*)&clientname, &size);
		    if(port2<0){
			warning("accept failed: %s. close port %d\n", strerror(errno), i);
			FD_CLR(i, &active_fd_set);
			close(i);
		    }else{
			info("port %d is connected\n", port2);
			FD_SET(port2, &active_fd_set);
		    }
		}else if(i==sock_local){
		    socklen_t size=sizeof(struct sockaddr_un);
		    struct sockaddr_un clientname;
		    int port2=accept(i, (struct sockaddr*)&clientname, &size);
		    if(port2<0){
			warning("accept failed: %s. close port %d\n", strerror(errno), i);
			FD_CLR(i, &active_fd_set);
			close(i);
		    }else{
			info("port %d is connected locally\n", port2);
			FD_SET(port2, &active_fd_set);
		    }
		}else{
		    /* Data arriving on an already-connected socket. Call responder to handle.
		       On return:
		       negative value: Close read of socket. 
		       -1: also close the socket.
		     */
		    int ans=responder(i);
		    if(ans<0){
			FD_CLR(i, &active_fd_set);
			if(ans==-1){
			    warning("close port %d\n", i);
			    close(i);
			}else{
			    warning("ans=%d is not understood.\n", ans);
			}
		    }
		}
	    }
	}
    }
    /* Error happened. We close all connections and this server socket.*/
    close(sock);
    close(sock_local);
    FD_CLR(sock, &active_fd_set);
    FD_CLR(sock_local, &active_fd_set);
    warning("listen_port exited\n");
    for(int i=0; i<FD_SETSIZE; i++){
	if(FD_ISSET(i, &active_fd_set)){
	    warning("sock %d is still connected\n", i);
	    close(i);
	    FD_CLR(i, &active_fd_set);
	}
    }
    usleep(100);
    sync();
}
コード例 #21
0
ファイル: udp_server.c プロジェクト: mdsteele/grpc
/* Prepare a recently-created socket for listening. */
static int prepare_socket(grpc_socket_factory *socket_factory, int fd,
                          const grpc_resolved_address *addr) {
  grpc_resolved_address sockname_temp;
  struct sockaddr *addr_ptr = (struct sockaddr *)addr->addr;
  /* Set send/receive socket buffers to 1 MB */
  int buffer_size_bytes = 1024 * 1024;

  if (fd < 0) {
    goto error;
  }

  if (grpc_set_socket_nonblocking(fd, 1) != GRPC_ERROR_NONE) {
    gpr_log(GPR_ERROR, "Unable to set nonblocking %d: %s", fd, strerror(errno));
    goto error;
  }
  if (grpc_set_socket_cloexec(fd, 1) != GRPC_ERROR_NONE) {
    gpr_log(GPR_ERROR, "Unable to set cloexec %d: %s", fd, strerror(errno));
    goto error;
  }

  if (grpc_set_socket_ip_pktinfo_if_possible(fd) != GRPC_ERROR_NONE) {
    gpr_log(GPR_ERROR, "Unable to set ip_pktinfo.");
    goto error;
  } else if (addr_ptr->sa_family == AF_INET6) {
    if (grpc_set_socket_ipv6_recvpktinfo_if_possible(fd) != GRPC_ERROR_NONE) {
      gpr_log(GPR_ERROR, "Unable to set ipv6_recvpktinfo.");
      goto error;
    }
  }

  GPR_ASSERT(addr->len < ~(socklen_t)0);
  if (bind_socket(socket_factory, fd, addr) < 0) {
    char *addr_str;
    grpc_sockaddr_to_string(&addr_str, addr, 0);
    gpr_log(GPR_ERROR, "bind addr=%s: %s", addr_str, strerror(errno));
    gpr_free(addr_str);
    goto error;
  }

  sockname_temp.len = sizeof(struct sockaddr_storage);

  if (getsockname(fd, (struct sockaddr *)sockname_temp.addr,
                  (socklen_t *)&sockname_temp.len) < 0) {
    goto error;
  }

  if (grpc_set_socket_sndbuf(fd, buffer_size_bytes) != GRPC_ERROR_NONE) {
    gpr_log(GPR_ERROR, "Failed to set send buffer size to %d bytes",
            buffer_size_bytes);
    goto error;
  }

  if (grpc_set_socket_rcvbuf(fd, buffer_size_bytes) != GRPC_ERROR_NONE) {
    gpr_log(GPR_ERROR, "Failed to set receive buffer size to %d bytes",
            buffer_size_bytes);
    goto error;
  }

  return grpc_sockaddr_get_port(&sockname_temp);

error:
  if (fd >= 0) {
    close(fd);
  }
  return -1;
}
コード例 #22
0
ファイル: elev_slave.c プロジェクト: PederAaby/Heisprosjekt
void start_elevator(){
  	elev_init();
    elev_goto_nearest_floor();
    init_buttonVectors();
    for (int i = 0; i < N_FLOORS; i++){
    		printf("%i\n", internalButtonVector[i]);
   		 }

    lastFloor = elev_get_floor_sensor_signal();
    pthread_mutex_init(&fileLock, NULL);
    pthread_mutex_lock(&fileLock);
    printf("Trying to read internal orders and set internalButtonVector\n");
    internalOrdersText = fopen("internal.txt", "r");
    int character;
    if (internalOrdersText != NULL){
    	for (int i = 0; i < N_FLOORS; i++){
    		character = fgetc(internalOrdersText);
    		if((character-48) == 1){
    			internalButtonVector[i] = 1;
    		}
    		else{
    			internalButtonVector[i] = 0;
    		}


    		printf("%i\n", internalButtonVector[i]);
             elev_set_button_lamp(BUTTON_COMMAND, i, internalButtonVector[i]);
   		 }
    
    fclose(internalOrdersText);
    }
    else{
    	printf("Inititating internalOrdersText\n");
    	init_internalOrdersText();
    }
    pthread_mutex_unlock(&fileLock);

	printf("Hva faen?\n");
	

	init_socket(&broadCastSocket);
	bind_socket(&broadCastSocket, BROADCAST_PORT, "255.255.255.255");
	
  	int reuseEnable = 1;
	if (setsockopt(broadCastSocket, SOL_SOCKET, SO_REUSEADDR, &reuseEnable, sizeof(reuseEnable)) < 0){
	    error("setsockopt");
	}

	init_socket(&sendSock);
	int broadcastEnable = 1;
	if (setsockopt(sendSock, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable))){
	  	error("setsockopt");
  	}

   pthread_create(&connectMasterThread, NULL, &connect_to_master, NULL);
   pthread_join(connectMasterThread, NULL);
   printf("First init finished, lytter på port: %i ip: %s\n", slp, masterIPAddr);


	pthread_mutex_init(&internalOrdersLock, NULL);
	pthread_create(&internalOrdersThread, NULL, &thread_check_internal_orders, NULL);

    pthread_mutex_init(&externalOrdersLock, NULL);
	pthread_create(&checkExternalOrderThread, NULL, &check_external_orders, NULL);

	pthread_mutex_init(&receiveLock, NULL);
	pthread_create(&receiveThread, NULL, &thread_udp_receive_from_master, NULL);

	pthread_mutex_init(&sendLock, NULL);
	pthread_create(&threadSendLocDir, NULL, &thread_send_loc_dir_master, NULL);


    printf("Initialization complete\n");
    sleep(1);
	elev_slave_waiting_with_network();
	pthread_join(internalOrdersThread, NULL);
	pthread_join(receiveThread, NULL);


}
コード例 #23
0
ファイル: gweb.c プロジェクト: bq/cervantes-conman
static int connect_session_transport(struct web_session *session)
{
	GIOFlags flags;
	int sk;

	sk = socket(session->addr->ai_family, SOCK_STREAM | SOCK_CLOEXEC,
			IPPROTO_TCP);
	if (sk < 0)
		return -EIO;

	if (session->web->index > 0) {
		if (bind_socket(sk, session->web->index,
					session->addr->ai_family) < 0) {
			debug(session->web, "bind() %s", strerror(errno));
			close(sk);
			return -EIO;
		}
	}

	if (session->flags & SESSION_FLAG_USE_TLS) {
		debug(session->web, "using TLS encryption");
		session->transport_channel = g_io_channel_gnutls_new(sk);
	} else {
		debug(session->web, "no encryption");
		session->transport_channel = g_io_channel_unix_new(sk);
	}

	if (session->transport_channel == NULL) {
		debug(session->web, "channel missing");
		close(sk);
		return -ENOMEM;
	}

	flags = g_io_channel_get_flags(session->transport_channel);
	g_io_channel_set_flags(session->transport_channel,
					flags | G_IO_FLAG_NONBLOCK, NULL);

	g_io_channel_set_encoding(session->transport_channel, NULL, NULL);
	g_io_channel_set_buffered(session->transport_channel, FALSE);

	g_io_channel_set_close_on_unref(session->transport_channel, TRUE);

	if (connect(sk, session->addr->ai_addr,
			session->addr->ai_addrlen) < 0) {
		if (errno != EINPROGRESS) {
			debug(session->web, "connect() %s", strerror(errno));
			close(sk);
			return -EIO;
		}
	}

	session->transport_watch = g_io_add_watch(session->transport_channel,
				G_IO_IN | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
						received_data, session);

	session->send_watch = g_io_add_watch(session->transport_channel,
				G_IO_OUT | G_IO_HUP | G_IO_NVAL | G_IO_ERR,
						send_data, session);

	return 0;
}
コード例 #24
0
ファイル: apmd.c プロジェクト: appleorange1/bitrig
int
main(int argc, char *argv[])
{
	const char *fname = apmdev;
	int ctl_fd, sock_fd, ch, suspends, standbys, resumes;
	int statonly = 0;
	int powerstatus = 0, powerbak = 0, powerchange = 0;
	int noacsleep = 0;
	struct timespec ts = {TIMO, 0}, sts = {0, 0};
	struct apm_power_info pinfo;
	time_t apmtimeout = 0;
	const char *sockname = sockfile;
	int kq, nchanges;
	struct kevent ev[2];
	int ncpu_mib[2] = { CTL_HW, HW_NCPU };
	int ncpu;
	size_t ncpu_sz = sizeof(ncpu);

	while ((ch = getopt(argc, argv, "aACdHLsf:t:S:")) != -1)
		switch(ch) {
		case 'a':
			noacsleep = 1;
			break;
		case 'd':
			debug = 1;
			break;
		case 'f':
			fname = optarg;
			break;
		case 'S':
			sockname = optarg;
			break;
		case 't':
			ts.tv_sec = strtoul(optarg, NULL, 0);
			if (ts.tv_sec == 0)
				usage();
			break;
		case 's':	/* status only */
			statonly = 1;
			break;
		case 'A':
			if (doperf != PERF_NONE)
				usage();
			doperf = PERF_AUTO;
			break;
		case 'C':
			if (doperf != PERF_NONE)
				usage();
			doperf = PERF_COOL;
			break;
		case 'L':
			if (doperf != PERF_NONE)
				usage();
			doperf = PERF_MANUAL;
			setperf(PERFMIN);
			break;
		case 'H':
			if (doperf != PERF_NONE)
				usage();
			doperf = PERF_MANUAL;
			setperf(PERFMAX);
			break;
		case '?':
		default:
			usage();
		}

	argc -= optind;
	argv += optind;

	if (argc != 0)
		usage();

	if (doperf == PERF_NONE)
		doperf = PERF_MANUAL;

	if (debug)
		openlog(__progname, LOG_CONS, LOG_LOCAL1);
	else {
		if (daemon(0, 0) < 0)
			error("failed to daemonize", NULL);
		openlog(__progname, LOG_CONS, LOG_DAEMON);
		setlogmask(LOG_UPTO(LOG_NOTICE));
	}

	(void) signal(SIGTERM, sigexit);
	(void) signal(SIGHUP, sigexit);
	(void) signal(SIGINT, sigexit);

	if ((ctl_fd = open(fname, O_RDWR)) == -1) {
		if (errno != ENXIO && errno != ENOENT)
			error("cannot open device file `%s'", fname);
	} else if (fcntl(ctl_fd, F_SETFD, FD_CLOEXEC) == -1)
		error("cannot set close-on-exec for `%s'", fname);

	sock_fd = bind_socket(sockname);

	if (fcntl(sock_fd, F_SETFD, FD_CLOEXEC) == -1)
		error("cannot set close-on-exec for the socket", NULL);

	power_status(ctl_fd, 1, &pinfo);

	if (statonly)
		exit(0);

	set_driver_messages(ctl_fd, APM_PRINT_OFF);

	kq = kqueue();
	if (kq <= 0)
		error("kqueue", NULL);

	EV_SET(&ev[0], sock_fd, EVFILT_READ, EV_ADD | EV_ENABLE | EV_CLEAR,
	    0, 0, NULL);
	if (ctl_fd == -1)
		nchanges = 1;
	else {
		EV_SET(&ev[1], ctl_fd, EVFILT_READ, EV_ADD | EV_ENABLE |
		    EV_CLEAR, 0, 0, NULL);
		nchanges = 2;
	}
	if (kevent(kq, ev, nchanges, NULL, 0, &sts) < 0)
		error("kevent", NULL);

	if (sysctl(ncpu_mib, 2, &ncpu, &ncpu_sz, NULL, 0) < 0)
		error("cannot read hw.ncpu", NULL);

	if (doperf == PERF_AUTO || doperf == PERF_COOL) {
		setperf(0);
		setperf(100);
	}
	for (;;) {
		int rv;

		sts = ts;

		if (doperf == PERF_AUTO || doperf == PERF_COOL) {
			sts.tv_sec = 1;
			perf_status(&pinfo, ncpu);
		}

		apmtimeout += sts.tv_sec;
		if ((rv = kevent(kq, NULL, 0, ev, 1, &sts)) < 0)
			break;

		if (apmtimeout >= ts.tv_sec) {
			apmtimeout = 0;

			/* wakeup for timeout: take status */
			powerbak = power_status(ctl_fd, 0, &pinfo);
			if (powerstatus != powerbak) {
				powerstatus = powerbak;
				powerchange = 1;
			}
		}

		if (!rv)
			continue;

		if (ev->ident == ctl_fd) {
			suspends = standbys = resumes = 0;
			syslog(LOG_DEBUG, "apmevent %04x index %d",
			    (int)APM_EVENT_TYPE(ev->data),
			    (int)APM_EVENT_INDEX(ev->data));

			switch (APM_EVENT_TYPE(ev->data)) {
			case APM_SUSPEND_REQ:
			case APM_USER_SUSPEND_REQ:
			case APM_CRIT_SUSPEND_REQ:
			case APM_BATTERY_LOW:
				suspends++;
				break;
			case APM_USER_STANDBY_REQ:
			case APM_STANDBY_REQ:
				standbys++;
				break;
#if 0
			case APM_CANCEL:
				suspends = standbys = 0;
				break;
#endif
			case APM_NORMAL_RESUME:
			case APM_CRIT_RESUME:
			case APM_SYS_STANDBY_RESUME:
				powerbak = power_status(ctl_fd, 0, &pinfo);
				if (powerstatus != powerbak) {
					powerstatus = powerbak;
					powerchange = 1;
				}
				resumes++;
				break;
			case APM_POWER_CHANGE:
				powerbak = power_status(ctl_fd, 0, &pinfo);
				if (powerstatus != powerbak) {
					powerstatus = powerbak;
					powerchange = 1;
				}
				break;
			default:
				;
			}

			if ((standbys || suspends) && noacsleep &&
			    power_status(ctl_fd, 0, &pinfo))
				syslog(LOG_DEBUG, "no! sleep! till brooklyn!");
			else if (suspends)
				suspend(ctl_fd);
			else if (standbys)
				stand_by(ctl_fd);
			else if (resumes) {
				do_etc_file(_PATH_APM_ETC_RESUME);
				syslog(LOG_NOTICE,
				    "system resumed from sleep");
			}

			if (powerchange) {
				if (powerstatus)
					do_etc_file(_PATH_APM_ETC_POWERUP);
				else
					do_etc_file(_PATH_APM_ETC_POWERDOWN);
				powerchange = 0;
			}

		} else if (ev->ident == sock_fd)
			switch (handle_client(sock_fd, ctl_fd)) {
			case NORMAL:
				break;
			case SUSPENDING:
				suspend(ctl_fd);
				break;
			case STANDING_BY:
				stand_by(ctl_fd);
				break;
			case HIBERNATING:
				hibernate(ctl_fd);
				break;
			}
	}
	error("kevent loop", NULL);

	return 1;
}
コード例 #25
0
ファイル: socket_server.c プロジェクト: puXiaoyi/skynet
// return type
// 执行管道指令,写入socket_message
static int
ctrl_cmd(struct socket_server *ss, struct socket_message *result) {
	int fd = ss->recvctrl_fd;
	// the length of message is one byte, so 256+8 buffer size is enough.
	// 读管道数据,相反的数据写入管道逻辑见send_request方法
	// len长度1个字节,所以缓冲区的长度为256足够
	uint8_t buffer[256];
	uint8_t header[2];
	// 先读2字节的头
	block_readpipe(fd, header, sizeof(header));
	int type = header[0];
	int len = header[1];
	// 再读剩余数据部分
	block_readpipe(fd, buffer, len);
	// ctrl command only exist in local fd, so don't worry about endian.
	switch (type) {
	case 'S':
		// PACCEPT -> CONNECTED 
		// PLISTEN -> LISTEN
		// 把套接字加入事件循环
		return start_socket(ss,(struct request_start *)buffer, result);
	case 'B':
		// 绑定套接字
		return bind_socket(ss,(struct request_bind *)buffer, result);
	case 'L':
		// 监听套接字
		return listen_socket(ss,(struct request_listen *)buffer, result);
	case 'K':
		// 关闭套接字
		return close_socket(ss,(struct request_close *)buffer, result);
	case 'O':
		// 打开套接字
		return open_socket(ss, (struct request_open *)buffer, result);
	case 'X':
		// 退出套接字
		result->opaque = 0;
		result->id = 0;
		result->ud = 0;
		result->data = NULL;
		return SOCKET_EXIT;
	case 'D':
		// 发送高优先级数据
		return send_socket(ss, (struct request_send *)buffer, result, PRIORITY_HIGH, NULL);
	case 'P':
		// 发送低优先级数据
		return send_socket(ss, (struct request_send *)buffer, result, PRIORITY_LOW, NULL);
	case 'A': {
		struct request_send_udp * rsu = (struct request_send_udp *)buffer;
		return send_socket(ss, &rsu->send, result, PRIORITY_HIGH, rsu->address);
	}
	case 'C':
		return set_udp_address(ss, (struct request_setudp *)buffer, result);
	case 'T':
		// 设置套接字
		setopt_socket(ss, (struct request_setopt *)buffer);
		return -1;
	case 'U':
		add_udp_socket(ss, (struct request_udp *)buffer);
		return -1;
	default:
		fprintf(stderr, "socket-server: Unknown ctrl %c.\n",type);
		return -1;
	};

	return -1;
}
コード例 #26
0
BOOL run_server_mode() {
	LPSTR instance_name = NULL;
	SOCKET local_socket = INVALID_SOCKET;
	SOCKADDR_BTH sock_addr_bth_local = { 0 };
	LPCSADDR_INFO addr_info = NULL;
	BOOL ret = FALSE;
	char end;

	local_socket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
	if (local_socket == INVALID_SOCKET) {
		print_error("socket()", WSAGetLastError());
		return FALSE;
	}

	ret = bind_socket(local_socket, &sock_addr_bth_local);
	if (!ret) {
		return FALSE;
	}

	addr_info = create_addr_info(&sock_addr_bth_local);
	if (!addr_info) {
		return FALSE;
	}

	ret = advertise_service_accepted(addr_info, &instance_name);
	if (!ret) {
		free(addr_info);
		if (instance_name) {
			free(instance_name);
		}
		return FALSE;
	}

	if (listen(local_socket, 4) == SOCKET_ERROR) {
		print_error("listen()", WSAGetLastError());
		free(addr_info);
		free(instance_name);
		return FALSE;
	}

	while (1) {
		printf("Waiting for client connection...");
		SOCKET client_socket = accept(local_socket, NULL, NULL);
		if (client_socket == INVALID_SOCKET) {
			print_error("accept()", WSAGetLastError());
			return FALSE;
		}
		printf("Client connected !\n");

		char *buffer = NULL;

		while(1) {

			if(!readBuffer(buffer,client_socket)) {
				return FALSE;
			}

			if(!strcmp(buffer,"openNoGba")){			
				WinExec("E:\\NO$GBA.2.6a\\NO$GBA.exe",1);
				free(buffer);
			}

			else if(!strcmp(buffer,"openMyComp")) {
				openMyComputer();
				free(buffer);
			}

			else if(!strcmp(buffer,"joystick")) {
				free(buffer);
				printf("Start joystick mode\n");
				while(1) {
					if(!readBuffer(buffer,client_socket)) {
						return FALSE;
					}

					joystickCMP(buffer); 

					if(!strcmp(buffer,"endJoystick")){
						free(buffer);
						break;
					}


					free(buffer);
				}
				printf("End joystick mode\n");
				continue;
			}

			else if(!strcmp(buffer,"openPlayer")) {
				free(buffer);
				WinExec("C:\\Program Files (x86)\\AIMP3\\AIMP3.exe",1);
				printf("Start player mode\n");
				while(1) {
					if(!readBuffer(buffer,client_socket)) {
						return FALSE;
					}

					playerCMP(buffer); 

					if(!strcmp(buffer,"endPlayer")){
						free(buffer);
						break;
					}


					free(buffer);
				}
				printf("End player mode\n");
				continue;
			}

			else if(!strcmp(buffer,"end")) {
				free(buffer);
				break;
			}

			else
				mouseCMP(buffer);
		}

		printf("Communication over\n");
		closesocket(client_socket);

		printf("Continue?(press 'n' to exit)");
		if(end = getch() == 'n') {
			break;
		}
	}

	free(addr_info);
	free(instance_name);
	closesocket(local_socket);
	return TRUE;
}
コード例 #27
0
ファイル: cnf_init.c プロジェクト: adamsbke/Synergy30
int cnf_init()
{
    FILE *fp;			    /* file pointer of init file */
    char buf[PATH_LEN];		    /* line buffer for input from init file */
    char *bufp;			    /* current index into buf */
    char *bp;			    /* temporary buffer pointer */
    char infile[PATH_LEN];	    /* name of init file */
    sng_map *link_pt; 
    int  idx,i, plist_cnt;
    dac_data_ot header;
    dac_link_ot links;
    dac_data_it stat;
    struct in_addr in;
    host_t *p_q;
    char mapid[TUPLENAME_LEN];

    if (gethostname(local_node, sizeof(local_node)) < 0)
    {
	perror("cnf_int: can't get local hostname"); 
	return(INIT_ER);
    }
// printf("starting app at (%s)\n",local_node);
    namtoad( local_node, local_addr );
    
    /* create the name of the init file from the module name (which
    comes from the CNF_MODULE logical name in the environment, suffixed
    with the value INIT_SUFFIX */

    tid_header = NULL;
    bp = getlognam("CNF_MODULE");
    if ( bp != NULL) { 
    	strcpy(infile, bp); 
    	strcat(infile, ".ini"); 
    	fp = fopen(infile, "r"); 
    }
    if  (( bp == NULL ) || (fp == NULL)) {
	if (!readn(0,(char *)&header, sizeof(dac_data_ot)))
	{
		printf("cnf_init: read from DAC header error.\n");
		close(0);
		return(INIT_ER);
	}
	sng_map_hd.f = ntohs(header.f);
	sng_map_hd.p = ntohs(header.p);
	sng_map_hd.t = ntohs(header.t);
	sng_map_hd.d = ntohs(header.d);
	sng_map_hd.link_cnt = ntohs(header.link_cnt) + 1; /* for dts ys96 */

	if (ntohs(header.protocol) == DAC_PROT_TCP)
	sprintf(sng_map_hd.protocol,"tcp");
	else sng_map_hd.protocol[0] = 0;
	strcpy(sng_map_hd.appid,header.appid);
	strcpy(sng_map_hd.name, header.name);
/*
printf("CNF_INIT: appid(%s) headerName(%s)\n",header.appid, header.name);
*/
	strcpy(sng_map_hd.csl_name,"");	
	idx = ntohs(header.link_cnt);
	sng_map_hd.link_hd = NULL;
	for (i=0; i<idx; i++)
	{
		if (!readn(0,(char *)&links, sizeof(dac_link_ot)))
		{
			printf("conf_init: read link from DAC error\n");
			close(0);
			return(INIT_ER);
		}
		link_pt = (sng_map *)malloc(sizeof(sng_map));
		link_pt->next = sng_map_hd.link_hd;
		sng_map_hd.link_hd = link_pt;
		link_pt->type = links.type;
		link_pt->dirn = links.dirn;
		strcpy(link_pt->ref_name,links.ref_name);
		strcpy(link_pt->obj_name,links.obj_name);
		strcpy(link_pt->phys_name,links.path);
		strcpy(link_pt->login, links.login);
		in.s_addr = links.host;
		strcpy(link_pt->cpu,inet_ntoa(in));
	}
	/* receive cpu_list here. YS f96 */
	get_cpu_list();

	/* now add the direct tuple space object */
	link_pt = (sng_map *)malloc(sizeof(sng_map));
	link_pt->next = sng_map_hd.link_hd;
	sng_map_hd.link_hd = link_pt;
	link_pt->type = 't';
	link_pt->dirn = '*';
	strcpy(link_pt->ref_name, "DynamicTS");
	strcpy(link_pt->obj_name, "DynamicTS");
	strcpy(link_pt->phys_name, "DynamicTS");
	strcpy(link_pt->login, getpwuid(getuid())->pw_name);
	link_pt->cpu[0] = 0; /* not used */
	link_pt->open = TRUE;
	link_pt->sd = get_socket();
	link_pt->ret_port = bind_socket(link_pt->sd, 0);
	link_pt->port = 0; /* To be filled by respective calls */
	/* end of direct tuple space addition */

	stat.status = htons(SUCCESS);
	stat.error = htons(DAC_ER_NOERROR);
	if (!writen(0,(char *)&stat, sizeof(dac_data_it)))
	{
		printf("cnf_init: send ACK error \n");
		close(0);
		return(INIT_ER);
	}
	close(0);
    	if (sng_map_hd.d > 1) cnf_print_map();
    	handles = (sng_map **) malloc(sizeof(sng_map *)*sng_map_hd.link_cnt);
    	for (sng_idx = 0 ; sng_idx < sng_map_hd.link_cnt ; sng_idx++) 
		handles[sng_idx] = NULL ; 
/*
	sng_map_hd.host = sng_gethostid(); 
*/
	sng_map_hd.host = header.host; 
        sprintf(buf, "sng$cid$%s", getpwuid(getuid())->pw_name);
       	if (!(sng_map_hd.cidport = pmd_getmap(buf,sng_map_hd.host,
			(u_short)PMD_PROT_TCP)))
    	{
	    printf("cnf_init_error: cidport lookup failure.\n");
	    exit(1);
    	}

	/* Reset the dts now. Ys96 */
	handles[0] = sng_map_hd.link_hd;
    	sng_idx = 1;	/* reset the open count */

//       printf("cnf_init done. host (%lu) \n",sng_map_hd.host);
        return;
    }
    else { /* Debug Mode */ 
    /* read the first line of the init file */
    if ((bufp = fgets(buf, PATH_LEN, fp)) == NULL)
    {
	printf("cnf_init: empty init file\n");
	return(INIT_ER);
    }

    /* read all the variable initialization lines */
    sscanf(bufp, "%s\n", buf);
    // This line makes debugging master dependent on cds host order: sng_map_hd.host = inet_addr(buf);
    sng_map_hd.host = sng_gethostid(); 
    status2=fscanf(fp, "%s", sng_map_hd.appid);
    status2=fscanf(fp, "%s", sng_map_hd.csl_name);
    status2=fscanf(fp, "%s", sng_map_hd.name);
    status2=fscanf(fp, "%s %s %s", buf, buf, sng_map_hd.protocol);
    status2=fscanf(fp, "%s %s %d", buf,buf,&sng_map_hd.f);
    status2=fscanf(fp,"%s %s %d", buf,buf,&sng_map_hd.p);
    status2=fscanf(fp,"%s %s %d", buf,buf,&sng_map_hd.t);
    status2=fscanf(fp,"%s %s %d",buf,buf,&sng_map_hd.d);
//    printf("CNF_INIT. f(%d) p(%d) t(%d)\n",
//	sng_map_hd.f, sng_map_hd.p, sng_map_hd.t);

    /* Add cpu_list here */
    status2=fscanf(fp, "%d\n", &plist_cnt);
    for (i=0; i<plist_cnt; i++)
    {
        if ((p_q = (host_t *) malloc(sizeof(host_t))) == NULL)
                             exit(E_MALLOC);
	strcpy(p_q->app_id, sng_map_hd.appid);
	status2=fscanf(fp, "%s %s", buf, p_q->login);
	strcpy(p_q->login, getpwuid(getuid())->pw_name);
	p_q->hostid = inet_addr(buf);
        p_q->next = NULL;
	sprintf(mapid, "sng$cid$%s", p_q->login);
	if (!(p_q->cidport = pmd_getmap(mapid,p_q->hostid,
		(u_short)PMD_PROT_TCP)))
	{
	    printf("cnf_init_error: remote cid port lookup failure.\n");
	    exit(1);
	}
        if (i == 0) list_host = end_host = p_q;
        else { 
		end_host->next = p_q;
                end_host = p_q;
        }
    }
    /* Now read arguments */
    bufp = fgets(buf, PATH_LEN, fp);
    idx = 0;
    while (*bufp != ':')
    {
	sscanf(bufp,"%s %s %s",buf,buf,sng_map_hd.args[idx]);
	// printf(" CNF_INIT: host-read(%s)\n", sng_map_hd.args[idx]); 
    	bufp = fgets(buf, PATH_LEN, fp);
	idx++;
    }
    /* Skip ":" */
    bufp = fgets(buf, PATH_LEN, fp);
    sng_map_hd.link_hd = NULL;
    sng_map_hd.link_cnt = 0;
    while (bufp != NULL) 
    {
	link_pt = (sng_map *)malloc(sizeof(sng_map));
	link_pt->next = sng_map_hd.link_hd;
	sng_map_hd.link_hd = link_pt;
	sscanf(bufp,"%c %c %s %s %s %s %s\n",
		&link_pt->type, 
		&link_pt->dirn,
		link_pt->ref_name,
		link_pt->obj_name,
		link_pt->cpu,
		link_pt->phys_name,
		link_pt->login);
	// printf(" CNF_INIT: ref(%s) objnm(%s) host(%s) pname(%s) login(%s)\n",
	// 	link_pt->ref_name,
	//	link_pt->obj_name,
	//	link_pt->cpu,
	//	link_pt->phys_name,
	//	link_pt->login);

	link_pt->open = FALSE;
	link_pt->port = 0;
	link_pt->ret_port = 0;
	bufp = fgets(buf, PATH_LEN, fp);
       	sng_map_hd.link_cnt++;	/* increment number of table entries */
    }
    /* Now add direct tuple space */
    sng_map_hd.link_cnt ++;
    link_pt = (sng_map *)malloc(sizeof(sng_map));
    link_pt->next = sng_map_hd.link_hd;
    sng_map_hd.link_hd = link_pt;
    link_pt->type = 't';
    link_pt->dirn = '*';
    strcpy(link_pt->ref_name, "DynamicTS");
    strcpy(link_pt->obj_name, "DynamicTS");
    strcpy(link_pt->phys_name, "DynamicTS");
    gethostname(link_pt->cpu, sizeof(link_pt->cpu));
    strcpy(link_pt->login, getpwuid(getuid())->pw_name);
    link_pt->open = TRUE;
    link_pt->sd = get_socket();
    link_pt->ret_port = bind_socket(link_pt->sd, 0);
    link_pt->port = 0; /* To be filled by respective calls later */
    /* end of dts ys96 */

    /* close init file */
    fclose(fp);
    if (sng_map_hd.d > 1) cnf_print_map();
    handles = (sng_map **) malloc(sizeof(sng_map *)*sng_map_hd.link_cnt);
    for (sng_idx = 0 ; sng_idx < sng_map_hd.link_cnt ; sng_idx++) 
	handles[sng_idx] = NULL ;

    sprintf(buf, "sng$cid$%s", getpwuid(getuid())->pw_name);
    if (!(sng_map_hd.cidport = pmd_getmap(buf,sng_map_hd.host,
		(u_short)PMD_PROT_TCP)))
    {
    	printf("cnf_init_error: cidport lookup failure.\n");
    	exit(1);
    }
//  printf("cnf_init. hostip(%ul) port(%d) appid(%s)\n",
//	sng_map_hd.host, sng_map_hd.cidport,sng_map_hd.appid);
    /* Reset the dts now. Ys96 */
    handles[0] = sng_map_hd.link_hd;
    sng_idx = 1;	/* reset the open count */
    } 
}
コード例 #28
0
ファイル: lispd_iface_mgmt.c プロジェクト: Alphalink/lispmob
void process_address_change (
        lispd_iface_elt     *iface,
        lisp_addr_t         new_addr)
{
    lisp_addr_t                 *iface_addr         = NULL;
    lispd_iface_mappings_list   *mapping_list       = NULL;
    lispd_mapping_list          *map_list   	    = NULL;
    int                         aux_afi             = 0;

    /* Check if the addres is a global address*/
    if (is_link_local_addr(new_addr) == TRUE){
        lispd_log_msg(LISP_LOG_DEBUG_2,"precess_address_change: the extractet address from the netlink "
                "messages is a local link address: %s discarded", get_char_from_lisp_addr_t(new_addr));
        return;
    }
    /* If default RLOC afi defined (-a 4 or 6), only accept addresses of the specified afi */
    if (default_rloc_afi != AF_UNSPEC && default_rloc_afi != new_addr.afi){
        lispd_log_msg(LISP_LOG_DEBUG_2,"precess_address_change: Default RLOC afi defined (-a #): Skipped %s address in iface %s",
                (new_addr.afi == AF_INET) ? "IPv4" : "IPv6",iface->iface_name);
        return;
    }
    /*
     * Actions to be done due to a change of address: SMR
     */

    switch (new_addr.afi){
    case AF_INET:
        iface_addr = iface->ipv4_address;
        break;
    case AF_INET6:
        iface_addr = iface->ipv6_address;
        break;
    }

    // Same address that we already have
    if (compare_lisp_addr_t(iface_addr,&new_addr)==0){
        lispd_log_msg(LISP_LOG_DEBUG_2,"precess_address_change: The detected change of address for interface %s "
                "doesn't affect",iface->iface_name);
#ifndef VPNAPI
        /* We must rebind the socket just in case the address is from a virtual interface who has changed its interafce number */
        switch (new_addr.afi){
        case AF_INET:
            bind_socket(iface->out_socket_v4,AF_INET,&new_addr,0);
            break;
        case AF_INET6:
            bind_socket(iface->out_socket_v6,AF_INET6,&new_addr,0);
            break;
        }
#endif
        return;
    }

#ifndef VPNAPI
    /*
     * Change source routing rules for this interface and binding
     */

    if (iface_addr->afi != AF_UNSPEC){
        del_rule(iface_addr->afi,
                0,
                iface->iface_index,
                iface->iface_index,
                RTN_UNICAST,
                iface_addr,
                (iface_addr->afi == AF_INET) ? 32 : 128,
                NULL,0,0);
    }
    add_rule(new_addr.afi,
            0,
            iface->iface_index,
            iface->iface_index,
            RTN_UNICAST,
            &new_addr,
            (new_addr.afi == AF_INET) ? 32 : 128,
            NULL,0,0);

    switch (new_addr.afi){
    case AF_INET:
        bind_socket(iface->out_socket_v4,AF_INET,&new_addr,0);
        break;
    case AF_INET6:
        bind_socket(iface->out_socket_v6,AF_INET6,&new_addr,0);
        break;
    }
#endif

    aux_afi = iface_addr->afi;
    // Update the new address
    copy_lisp_addr(iface_addr, &new_addr);


    /* The interface was down during initial configuratiopn process and now it is up. Activate address */
    if (aux_afi == AF_UNSPEC){
        lispd_log_msg(LISP_LOG_DEBUG_1,"process_address_change: Activating the locator address %s"
                , get_char_from_lisp_addr_t(new_addr));
        activate_interface_address(iface, new_addr);
        if (iface->status == UP){
            iface_balancing_vectors_calc(iface);

            /*
             * If no default control and data interface, recalculate it
             */

            if ((default_ctrl_iface_v4 == NULL && new_addr.afi == AF_INET) ||
                    (default_ctrl_iface_v6 == NULL && new_addr.afi == AF_INET6)){
                lispd_log_msg(LISP_LOG_DEBUG_2,"No default control interface. Recalculate new control interface");
                set_default_ctrl_ifaces();
            }

            if ((default_out_iface_v4 == NULL && new_addr.afi == AF_INET) ||
                    (default_out_iface_v6 == NULL && new_addr.afi == AF_INET6)){
                lispd_log_msg(LISP_LOG_DEBUG_2,"No default output interface. Recalculate new output interface");
                set_default_output_ifaces();
            }
        }
    }

    lispd_log_msg(LISP_LOG_DEBUG_1,"precess_address_change: New address detected for interface %s -> %s",
            iface->iface_name, get_char_from_lisp_addr_t(new_addr));

    mapping_list = iface->head_mappings_list;
    /* Sort again the locators list of the affected mappings*/
    while (mapping_list != NULL){
        if (aux_afi != AF_UNSPEC && // When the locator is activated, it is automatically sorted
                ((new_addr.afi == AF_INET && mapping_list->use_ipv4_address == TRUE) ||
                        (new_addr.afi == AF_INET6 && mapping_list->use_ipv6_address == TRUE))){
            sort_locators_list_elt (mapping_list->mapping, iface_addr);
        }
        mapping_list = mapping_list->next;
    }

    /* Indicate change of address in the interface */

    switch (new_addr.afi){
    case AF_INET:
        iface->ipv4_changed = TRUE;
        break;
    case AF_INET6:
        iface->ipv6_changed = TRUE;
        break;
    }

    /* Check if the new address is behind NAT */

    if(nat_aware==TRUE){
        if (iface->status == UP && new_addr.afi == AF_INET){
        	map_list = get_mappings_from_iface(iface);
        	restart_info_request_process(map_list,iface->ipv4_address);
        	free_mapping_list(map_list,FALSE);
        }
    }

    /* Reprograming SMR timer*/
    if (smr_timer == NULL){
        smr_timer = create_timer (SMR_TIMER);
    }

    start_timer(smr_timer, LISPD_SMR_TIMEOUT,(timer_callback)init_smr, NULL);
}
コード例 #29
0
static int
serve_threads(int nthreads, int port, const char *db_path, void *zmq_ctx,
              const char *send_endpoint, const char *recv_endpoint,
              const char *log_base_path)
{
  int nfd;
  uint32_t i;
  thd_data thds[nthreads];

  if ((nfd = bind_socket(port)) < 0) {
    print_error("cannot bind socket. please check port number with netstat.");
    return -1;
  }

  for (i = 0; i < nthreads; i++) {
    memset(&thds[i], 0, sizeof(thds[i]));
    if (!(thds[i].base = event_init())) {
      print_error("error in event_init() on thread %d.", i);
    } else {
      if (!(thds[i].httpd = evhttp_new(thds[i].base))) {
        print_error("error in evhttp_new() on thread %d.", i);
      } else {
        int r;
        if ((r = evhttp_accept_socket(thds[i].httpd, nfd))) {
          print_error("error in evhttp_accept_socket() on thread %d.", i);
        } else {
          if (send_endpoint) {
            if (!(thds[i].zmq_sock = zmq_socket(zmq_ctx, ZMQ_PUB))) {
              print_error("cannot create zmq_socket.");
            } else if (zmq_connect(thds[i].zmq_sock, send_endpoint)) {
              print_error("cannot connect zmq_socket.");
              zmq_close(thds[i].zmq_sock);
              thds[i].zmq_sock = NULL;
            } else {
              uint64_t hwm = 1;
              zmq_setsockopt(thds[i].zmq_sock, ZMQ_HWM, &hwm, sizeof(uint64_t));
            }
          } else {
            thds[i].zmq_sock = NULL;
          }
          if (!(thds[i].ctx = grn_ctx_open(0))) {
            print_error("error in grn_ctx_open() on thread %d.", i);
          } else if (grn_ctx_use(thds[i].ctx, db)) {
            print_error("error in grn_db_open() on thread %d.", i);
          } else {
            GRN_TEXT_INIT(&(thds[i].cmd_buf), 0);
            thds[i].log_base_path = log_base_path;
            thds[i].thread_id = i;
            evhttp_set_gencb(thds[i].httpd, generic_handler, &thds[i]);
            evhttp_set_timeout(thds[i].httpd, 10);
            {
              struct timeval tv = {1, 0};
              evtimer_set(&(thds[i].pulse), timeout_handler, &thds[i]);
              evtimer_add(&(thds[i].pulse), &tv);
            }
            if ((r = pthread_create(&(thds[i].thd), NULL, dispatch, thds[i].base))) {
              print_error("error in pthread_create() on thread %d.", i);
            }
          }
        }
      }
    }
  }

  /* recv thread from learner */
  if (recv_endpoint) {
    recv_thd_data rthd;
    rthd.db_path = db_path;
    rthd.recv_endpoint = recv_endpoint;
    rthd.zmq_ctx = zmq_ctx;

    if (pthread_create(&(rthd.thd), NULL, recv_from_learner, &rthd)) {
      print_error("error in pthread_create() on thread %d.", i);
    }
    pthread_join(rthd.thd, NULL);
  } else {
    while (loop) { sleep(1000); }
  }

  /* join all httpd thread */
  for (i = 0; i < nthreads; i++) {
    if (thds[i].thd) {
      pthread_join(thds[i].thd, NULL);
    }
    cleanup_httpd_thread(&(thds[i]));
  }
  return 0;
}
コード例 #30
0
ファイル: bind.c プロジェクト: CERT-Polska/hsn2-razorback
int ssh_bind_listen(ssh_bind sshbind) {
  const char *host;
  socket_t fd;
  int rc;

  if (ssh_init() < 0) {
    ssh_set_error(sshbind, SSH_FATAL, "ssh_init() failed");
    return -1;
  }

  if (sshbind->dsakey == NULL && sshbind->rsakey == NULL) {
      ssh_set_error(sshbind, SSH_FATAL,
              "DSA or RSA host key file must be set before listen()");
      return SSH_ERROR;
  }

  if (sshbind->dsakey) {
      rc = ssh_pki_import_privkey_file(sshbind->dsakey,
                                       NULL,
                                       NULL,
                                       NULL,
                                       &sshbind->dsa);
      if (rc == SSH_ERROR) {
          ssh_set_error(sshbind, SSH_FATAL,
                  "Failed to import private DSA host key");
          return SSH_ERROR;
      }

      if (ssh_key_type(sshbind->dsa) != SSH_KEYTYPE_DSS) {
          ssh_set_error(sshbind, SSH_FATAL,
                  "The DSA host key has the wrong type");
          ssh_key_free(sshbind->dsa);
          return SSH_ERROR;
      }
  }

  if (sshbind->rsakey) {
      rc = ssh_pki_import_privkey_file(sshbind->rsakey,
                                       NULL,
                                       NULL,
                                       NULL,
                                       &sshbind->rsa);
      if (rc == SSH_ERROR) {
          ssh_set_error(sshbind, SSH_FATAL,
                  "Failed to import private RSA host key");
          return SSH_ERROR;
      }

      if (ssh_key_type(sshbind->rsa) != SSH_KEYTYPE_RSA &&
          ssh_key_type(sshbind->rsa) != SSH_KEYTYPE_RSA1) {
          ssh_set_error(sshbind, SSH_FATAL,
                  "The RSA host key has the wrong type");
          ssh_key_free(sshbind->rsa);
          return SSH_ERROR;
      }
  }

  if (sshbind->bindfd == SSH_INVALID_SOCKET) {
      host = sshbind->bindaddr;
      if (host == NULL) {
          host = "0.0.0.0";
      }

      fd = bind_socket(sshbind, host, sshbind->bindport);
      if (fd == SSH_INVALID_SOCKET) {
          ssh_key_free(sshbind->dsa);
          ssh_key_free(sshbind->rsa);
          return -1;
      }
      sshbind->bindfd = fd;

      if (listen(fd, 10) < 0) {
          ssh_set_error(sshbind, SSH_FATAL,
                  "Listening to socket %d: %s",
                  fd, strerror(errno));
          close(fd);
          ssh_key_free(sshbind->dsa);
          ssh_key_free(sshbind->rsa);
          return -1;
      }
  } else {
      SSH_LOG(sshbind, SSH_LOG_INFO, "Using app-provided bind socket");
  }
  return 0;
}