Esempio n. 1
0
int Session::on_read_event()
{
    int ret;
    while (true)
    {
        if (!m_has_head)
        {
            ret = read_head();
            if (ret < 0)
            {
                return -1;
            }
            if (ret == SESSION_RET_NO_DATA)
            {
                return 0;
            }
            if (m_msg_type == MSG_HEART_BEAT)
            {
                if (g_is_master)
                {
                    update_active_time();
                }
                else
                {
                    struct commu_msg msg;
                    msg.ip = get_cli_addr();
                    msg.msg = MSG_HEART_BEAT;
                    notify_master(msg);
                }
                continue;
            }
            m_has_head = true;
            m_buff = (u_char *)glb_mempool()->get(m_msg_len);
        }
        int n_read = readn(m_sockfd, &m_buff[m_n_read], m_msg_len - m_n_read);
        if (n_read < 0)
        {
            logerr("socket broken\n");
            m_msg_len = 0;
            m_has_head = false;
            return -1;
        }
        m_n_read += n_read;
        if (m_n_read == m_msg_len)
        {
            write_msg(m_buff, m_msg_len);
            reset_buffer();
        }
    }
    return 0;

}
Esempio n. 2
0
/*
 * on the server side of the negotiation protocol, we read
 * the client response and then run the negotiated function.
 * in some cases (e.g., TLS) the negotiated function needs to
 * use v->datafd directly and be sure that no data has been
 * buffered away in the Bio.  since we know the client is waiting
 * for our response, it won't have sent any until we respond.
 * thus we read the response with vncrdstringx, which goes
 * behind bio's back.
 */
char*
vncrdstringx(Vnc *v)
{
	char tmp[4];
	char *s;
	ulong len;

	assert(Bbuffered(&v->in) == 0);
	if(readn(v->datafd, tmp, 4) != 4){
		fprint(2, "cannot rdstringx: %r");
		vnchungup(v);
	}
	len = LONG(tmp);
	s = malloc(len+1);
	assert(s != nil);
	if(readn(v->datafd, s, len) != len){
		fprint(2, "cannot rdstringx len %lud: %r", len);
		vnchungup(v);
	}
	s[len] = '\0';
	return s;
}
Esempio n. 3
0
int priv_sock_get_int(int fd)
{
	int the_int;
	int ret;
	ret = readn(fd, &the_int, sizeof(the_int));
	if (ret != sizeof(the_int))
	{
		fprintf(stderr, "priv_sock_get_int error\n");
		exit(EXIT_FAILURE);
	}

	return the_int;
}
Esempio n. 4
0
int sckClient_rcv(void *handle, unsigned char *out, int *outlen)
{
    int ret = 0;
    SckHandle *tmp = handle;
    ret = read_timeout(tmp->sockfd, tmp->recvtime);
    if(ret < 0){
        if(ret == -1 && errno == ETIMEDOUT){
            ret = SCK_ERRTIMEOUT;
            printf("sckClient_rcv() err: %d\n", ret);
            return ret;
        }

        return ret;
    }
    int netdatalen = 0;
    ret = readn(tmp->sockfd, &netdatalen, 4);
    if(ret == -1 ){
        printf("func sckClient_rcv() first err: %d\n", ret);
        return ret;
    }else if(ret < 4){
        ret = SCK_ERRPEERCLOSED;
        printf("func sckClient_rcv() first err: %d\n", ret);
        return ret;
    }
    int n;
    n = ntohl(netdatalen);
    ret = readn(tmp->sockfd, out, n);
    if(ret == -1 ){
        printf("func sckClient_rcv() second err: %d\n", ret);
        return ret;
    }else if(ret < n){
        ret = SCK_ERRPEERCLOSED;
        printf("func sckClient_rcv() second err: %d\n", ret);
        return ret;
    }
    *outlen = n;

    return 0;
}
Esempio n. 5
0
char priv_sock_get_result(int fd)
{
    char res;
    int ret;
    ret = readn(fd, &res, sizeof(res));
    if (ret != sizeof(res))
    {
        fprintf(stderr, "priv_sock_get_result error\n");
        exit(EXIT_FAILURE);
    }

    return res;
}
Esempio n. 6
0
static void
xread(Ioclust *c)
{
	int n;
	Xdata *dev;

	dev = c->dev;
	seek(dev->dev, (vlong)c->addr * Sectorsize, 0);
	n = readn(dev->dev, c->iobuf, BUFPERCLUST*Sectorsize);
	if(n < Sectorsize)
		error("I/O read error");
	c->nbuf = n/Sectorsize;
}
Esempio n. 7
0
int usc_mrcp_asr_destroy(HANDLE_MRCPINTF asr)
{
    char buf[48];
    off_t offset = 0;
    PUSH_FUN(buf, offset, sizeof(buf));
    PUSH_HEAD(buf, offset, sizeof(buf));

    writen(asr, buf, offset + 4);
    /*read return value*/
    readn(asr, buf, 8);
    close(asr);
    return 0;
}
Esempio n. 8
0
File: tarfs.c Progetto: aahud/harvey
char *
doread(Ram *r, int64_t off, int32_t cnt)
{
	int n;

	seek(tapefile, Tblock*r->addr + off, 0);
	if (cnt > sizeof dblock.tbuf)
		error("read too big");
	n = readn(tapefile, dblock.tbuf, cnt);
	if (n != cnt)
		memset(dblock.tbuf + n, 0, cnt - n);
	return dblock.tbuf;
}
Esempio n. 9
0
ssize_t readline(int sockfd, void *buf, size_t maxline)
{
    int ret;
    int nread;
    char *bufp = (char *)buf;
    int nleft = maxline;
    while(nleft > 0)
    {
        ret = recv_peek(sockfd, bufp, nleft);
        if(ret < 0)
            return ret;
        else if(ret == 0)
            return 0;

        nread = ret;
        int i;
        for(i=0; i<nread; i++){
            if(bufp[i] == '\n') {
                ret = readn(sockfd, bufp, i + 1);
                if( ret != i+1)
                    exit(-1);

                return ret;
            }
        }
        if(nread > nleft)
            exit(-1);

        nleft -= nread;
        ret = readn(sockfd, bufp, nread);
        if(ret != nread)
            exit(-1);

        bufp += nread;

    }

    return -1;
}
Esempio n. 10
0
ssize_t readline(int fd, void *buf, size_t maxlen)
{
	size_t nleft = maxlen - 1;
	char *bufp = (char *)buf;
	ssize_t total = 0;
	ssize_t nread;

	while (nleft > 0) {
		//recv+peek为预读取
		nread = recv_peek(fd, bufp, nleft);
		if (nread <= 0)
			return nread;

		//检查此段内有无\n
		int i;
		for (i = 0; i < nread; ++i) {
			if (bufp[i] == '\n') {
				//找到\n后读取退出
				size_t nsize = i + 1;
				if (readn(fd, bufp, nsize) != nsize)
					return -1;
				bufp += nsize;
				*bufp = '\0';
				total += nsize;
				return total;
			}
		}

		//到此步说明没有找到\n,继续
		if (readn(fd, bufp, nread) != nread)
			return -1;
		bufp += nread;
		total += nread;
		nleft -= nread;
	}
	//读取到最大长度,返回
	*bufp = '\0';
	return maxlen - 1;
}
Esempio n. 11
0
ssize_t SocketIO::readline(char * buf, size_t maxlen)
{
	size_t nleft = maxlen - 1;
	char * pbuf = buf;
	ssize_t nread;
	size_t total = 0;

	while(nleft > 0)
	{
		nread = recv_peek(pbuf, nleft);
		if(nread <= 0)
			return nread;
		int i;
		for(i = 0; i != nread; ++i)
		{
			 //当找到'\n'
			if(pbuf[i] == '\n')
			{
				size_t nsize = i + 1;
				if(static_cast<ssize_t>(nsize) 
						!= readn(pbuf, nsize))
					return -1;
				pbuf += nsize;
				total += nsize;
				*pbuf = 0;
				return total;
			}
		}

		//当没有找到'\n'
		if(readn(pbuf, nread) != nread)
			return -1;
		total += nread;
		pbuf += nread;
		nleft -= nread;
	}
	*pbuf = 0;
	return maxlen - 1;
}
Esempio n. 12
0
File: io.c Progetto: spolu/ur
char *
readline (int fd)
{
	char * line;
	char * ptr;
	int i = 0;
	int nread = 0;
	int len = 0;
	int buflen = 0;
	
	
	if ((line = (char *) malloc (LINE_BUF_SIZE * sizeof (char))) == NULL)
		return NULL;
	ptr = line;
	
	/* we accept \r\n and \n as endline. */
	
	while (len < (MAX_LINE_BUF_SIZE-1) && (nread = readn (fd, ptr, 1)) == 1
		   && *ptr != '\n') {
		
		if (*ptr != '\r') {
			len += nread;
			ptr += nread;
			buflen += nread;
			
			if (buflen == LINE_BUF_SIZE) {
				i ++;
				if ((line = realloc (line, (i+1) * LINE_BUF_SIZE * sizeof (char))) == NULL) {
					free (line);
					return NULL;
				}
				ptr = line + i * LINE_BUF_SIZE;
				buflen = 0;
			}
		}
	}
	
	/* EOF */
	if (len == 0 && nread == 0) {
		free (line);
		return NULL;
	}
	
	if (nread == -1 || len >= MAX_LINE_BUF_SIZE) {
		free (line);
		return NULL;
	}
		
	line [len] = 0;
	return line;
}
Esempio n. 13
0
int main (int argc, char *argv[]) {
    double C = 60 * log(2);
    double PI = 2 * acos(0);
    fread_unlocked(s, sizeof(char), 10 * 1024 * 1024, stdin);
    readn();
    int i, t = n;
    for (I = 0; I < t; I += 1) {
        readn_signed();
        a = n;
        readn_signed();
        b = n;
        theta = atan2 (b, a) / PI;
        r = log( (double)( a * a + b * b ) );
        written = 1;


        for (k = 1; k <= 4; k += 1) {

            if ( k * r <= C && fabs ( k * theta - (int)(k * theta + 0.5) ) < 0.00001 ) {

                writen(k);
                written = 101;
                break;
            }
        }
        if ( written != 101 ) {
            out[++wcount] = 'T';
            out[++wcount] = 'O';
            out[++wcount] = 'O';
            out[++wcount] = ' ';
            out[++wcount] = 'C';
            out[++wcount] = 'O';
            out[++wcount] = 'M';
            out[++wcount] = 'P';
            out[++wcount] = 'L';
            out[++wcount] = 'I';
            out[++wcount] = 'C';
            out[++wcount] = 'A';
            out[++wcount] = 'T';
            out[++wcount] = 'E';
            out[++wcount] = 'D';

        }

        out[++wcount] = '\n';
    }

    fwrite_unlocked(out, 1, wcount + 1, stdout);

    return 0;
}
Esempio n. 14
0
/* elf ----------------------------------------------------------------------*/
void
elf(int fd_s, int fd_d, Elf32_Word p_type, Elf32_Word p_flags,
					Elf32_Addr* addr, int* size, int flag)
{
	int		i;	
	Elf32_Ehdr	e_eh;
	static Elf32_Phdr	e_ph[32];

	lseek(fd_s, 0, SEEK_SET);	/* rewind */

	readn(fd_s, &e_eh, sizeof(Elf32_Ehdr));
	lseek(fd_s, e_eh.e_phoff, SEEK_SET);
	readn(fd_s, (char*)e_ph, e_eh.e_phentsize * e_eh.e_phnum);

printf("#-----------------------------------------------------------------#\n");
printf("# [t]ype, [f]lag, [v]addr, [m]emsz, [s]filesz, [o]ffset           #\n");
printf("# e_eh.e_phnum = %d\n", e_eh.e_phnum);
	for (i = 0 ; i < e_eh.e_phnum ; i ++) {
printf("# ph[%d]: t = 0x%x, f = 0x%x, v = 0x%x, m = 0x%x, s = 0x%x o = %d\n", 
	i, e_ph[i].p_type, e_ph[i].p_flags, e_ph[i].p_vaddr, e_ph[i].p_memsz,
		e_ph[i].p_filesz, e_ph[i].p_offset);
		if (e_ph[i].p_type == p_type &&
				e_ph[i].p_flags == p_flags) {
			/* do everything ------------------------------------*/
			if (flag) {
				write_space(fd_d,
					(int)(e_ph[i].p_vaddr - *addr) - *size);
			}
			lseek(fd_s, e_ph[i].p_offset, SEEK_SET);
			readn(fd_s, buf, e_ph[i].p_filesz);
			writen(fd_d, buf, e_ph[i].p_filesz);
			*addr = e_ph[i].p_vaddr;
			*size = e_ph[i].p_memsz;
printf("# virtual address = 0x%x, size = 0x%x\n", *addr, *size);
			break;
		}
	}
}
Esempio n. 15
0
int sckServer_rcv(int connfd, unsigned char *out, int *outlen, int timeout){
    int ret = 0;
	printf("sckServer_rcv() connfd=%d\n", connfd);
    ret = read_timeout(connfd, timeout);
    if(ret < 0){
        if(ret == -1 && errno == ETIMEDOUT){
            ret = SCK_ERRTIMEOUT;
            printf("sckServer_rcv() read timeout err: %d\n", ret);
            return ret;
        }

        return ret;
    }
    int netdatalen = 0;
    ret = readn(connfd, &netdatalen, 4);
    if(ret == -1 ){
        printf("func sckServer_rcv() first err: %d\n", ret);
        return ret;
    }else if(ret < 4){
        ret = SCK_ERRPEERCLOSED;
        printf("func sckServer_rcv() first err: %d\n", ret);
        return ret;
    }
    int n;
    n = ntohl(netdatalen);
    ret = readn(connfd, out, n);
    if(ret == -1 ){
        printf("func sckServer_rcv() second err: %d\n", ret);
        return ret;
    }else if(ret < n){
        ret = SCK_ERRPEERCLOSED;
        printf("func sckServer_rcv() second err: %d\n", ret);
        return ret;
    }
    *outlen = n;

    return 0;
}
Esempio n. 16
0
static void
tcpreader(void *a)
{
	Session *s = a;
	uint8_t *buf;
	int buflen = smbglobals.maxreceive + 4;
	buf = nbemalloc(buflen);
	for (;;) {
		int n;
		uint8_t flags;
		uint16_t length;

		n = readn(s->fd, buf, 4);
		if (n != 4) {
		die:
			free(buf);
			if (s->state == Connected)
				(*s->write)(s, nil, -1);
			deletesession(s);
			return;
		}
		flags = buf[1];
		length = nhgets(buf + 2) | ((flags & 1) << 16);
		if (length > buflen - 4) {
			print("nbss: too much data (%ud)\n", length);
			goto die;
		}
		n = readn(s->fd, buf + 4, length);
		if (n != length)
			goto die;
		if (s->state == Connected) {
			if ((*s->write)(s, buf + 4, length) != 0) {
				s->state = Dead;
				goto die;
			}
		}
	}
}
Esempio n. 17
0
File: gzip.c Progetto: strake/gzip
void ungz (int ifd, int ofd) {
	uint8_t x[10];
	switch (readn (ifd, x, 10)) {
	case  0: return;
	case 10: break;
	default: errx (-1, "not in gz format");
	}
	if (x[0] != 0x1F || x[1] != 0x8B) errx (-1, "not in gz format");
	if (x[2] != 8) errx (-1, "unknown z-algorithm: 0x%0hhX", x[2]);
	if (x[3] & 1 << 2) /* FEXTRA */ {
		uint16_t n;
		uint8_t n_[2], _[1];
		readn (ifd, n_, 2);
		for (n = n_[0] << 0 | n_[1] << 8; n-- > 0; readn (ifd, _, 1));
	}
	if (x[3] & 1 << 3) /* FNAME    */ skipString (ifd);
	if (x[3] & 1 << 4) /* FCOMMENT */ skipString (ifd);
	if (x[3] & 1 << 1) /* FCRC */ {
		uint16_t _[1];
		readn (ifd, _, 2);
	}
	go (0, ifd, ofd);
}
Esempio n. 18
0
static uchar*
load(int fd, ulong off, int size)
{
	uchar *a;

	a = malloc(size);
	if(a == nil)
		return nil;
	if(seek(fd, off, 0) < 0 || readn(fd, a, size) != size){
		free(a);
		return nil;
	}
	return a;
}
Esempio n. 19
0
void do_service(int peerfd)
{
    char recvbuf[1024];
    int ret;
    while(1)
    {
        memset(recvbuf, 0, sizeof recvbuf);
        int data;
        int len;
        readn(peerfd, &data, sizeof data);
        len = htonl(data);
        ret = readn(peerfd, recvbuf, len);
        if(ret == -1)
            return;
        else if(ret == 0)
            break;
        else
        {
            writen(peerfd, &data, sizeof data);
            writen(peerfd, recvbuf,len);
        }
    }
}
Esempio n. 20
0
File: pe.c Progetto: GYGit/reactos
static int
readblock(void *fd, DwarfBlock *b, ulong off, ulong len)
{
	b->data = malloc(len);
	if(b->data == nil)
		return -1;
	if(!seek(fd, off, 0) || !readn(fd, (char *)b->data, len)){
		free(b->data);
		b->data = nil;
		return -1;
	}
	b->len = len;
	return 0;
}
Esempio n. 21
0
/*━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━*/
 recvtext(int sd,char name[16],char len[20])
 {
 FILE 	*fp;
 char 	recvbuf[1280];
 int 	i,count,fsize;

  	fp=fopen(name,"w");
	int l = atoi(len);	
  	if(fp==NULL)return(-2); 
  	count=l/1280;
  	fsize=l%1280;
  	for(i=0;i<count;i++)
		{
  		readn(sd,recvbuf,1280);
		fwrite(recvbuf,1,1280,fp);
		}
  	if(fsize >0){
		readn(sd,recvbuf,fsize);	
		fwrite(recvbuf,1,fsize,fp);
		}
  	fclose(fp);
  	return 0;
 	}
Esempio n. 22
0
/*	Function invoked for sub-station (i.e., child process of the main server process)	*/
int sub_station() {
	
	int tcp_sock, sub_sock, s;
	in_port_t self_port;
	struct sockaddr_in sub_self, curr_client;
	Message from_msg, to_msg;
	
	self_port = getpid();
	
	printf("[Initiating sub-station %d]\n", self_port);
	
	memset((char*)&sub_self, 0, sizeof(struct sockaddr_in));
	memset((char*)&curr_client, 0, sizeof(struct sockaddr_in));
	sub_self.sin_family = AF_INET;
	sub_self.sin_port = htons(self_port);
	sub_self.sin_addr.s_addr = inet_addr(LOOPBACK_ADDR);
	
	// Let the main station(parent process) transmit the necessary infos to the client first
	//sleep(2);

	if((tcp_sock=socket(AF_INET, SOCK_STREAM, 0)) == -1)
		goto err_ret;
	if(bind(tcp_sock, (struct sockaddr*)&sub_self, sizeof(sub_self)) == -1)
		goto err_ret;
	if(listen(tcp_sock, 1) == -1)
		goto err_ret;
	s = sizeof(curr_client);
	if((sub_sock=accept(tcp_sock, (struct sockaddr*)&curr_client, &s)) == -1)
		goto err_ret;
	
	printf("[Sub-station %d]: Connection with host %d was successful\n", htons(self_port), htons(curr_client.sin_port));

	// Start communication with the host('A' or 'B')
	printf("[Begin communication]\n");
	while(1) {
		// readn(sub_sock, (Message*)&from_msg, sizeof(Message));
		readn(sub_sock, (char*)&from_msg, sizeof(Message));
		if(from_msg.header.type == MSG_DELIVER) {	//Deliver mesg to host B
			msg_deliver(&from_msg);
		} else {	// Else consider illegal message
			msg_reject(&curr_client);
		}
	}
	
	close(sub_sock);
	close(tcp_sock);
err_ret:
	fprintf(stderr, "[ERROR: Sub-station failure]\n");
	return EXIT_FAILURE;
}
Esempio n. 23
0
//: MSG_MA
int interface_manage_permision(int pSockFD, I_REQUEST_H *header)
{
	int ret = M_TRUE ;
	int rlen, wlen ;

	I_MP_IN in ;
	I_RESULT_H	i_result_h ;

	fd_set readset ;
	struct timeval tmv ;

	FD_ZERO(&readset) ;
	FD_SET(pSockFD, &readset) ;
	tmv.tv_sec = 30 ; tmv.tv_usec = 0 ;

	if(select(pSockFD+1, &readset, NULL, NULL, &tmv) < 0)  {
		printLog(HEAD, "ERR: (%.18s)select Error : SOCKET(%d) CLOSE\n", 
			header->productid, pSockFD) ;
		return M_FAIL ;
	}
	if (!FD_ISSET(pSockFD, &readset)) { // 30초동안 msgid를 받지 못한 경우,
		printLog(HEAD, "ERR: (%.18s)SockFD(%d) TimeOut wait read_time(%d)\n", 
			header->productid, pSockFD, tmv.tv_sec) ;
		return M_FAIL ;
	}

	memset(&in, 0, sizeof(I_MP_IN)) ;
	if((rlen = readn(pSockFD, &in, sizeof(I_MP_IN))) != sizeof(I_MP_IN)) {
		printLog(HEAD, "ERR: (%.18s)Socket Read Fail(%d/%d)\n", header->productid, rlen, sizeof(I_MP_IN));
		return M_FAIL ;
	}
	in.flag = ntohl(in.flag) ;
	printLog(HEAD, "READ: (LEN:%d) (%.18s) I_MP_IN-FLAG[%d]\n", rlen, header->productid, in.flag) ;

	ret = db_manage_permision(header, &in) ;
	printLog(HEAD, "(%.18s) db_manage_permision() RET(%d)\n", header->productid, ret) ;
	
	i_result_h.error = htonl(ret) ;
	i_result_h.count = htonl(0) ;
	i_result_h.total = htonl(0) ;

	if((wlen = writen(pSockFD, &i_result_h, sizeof(I_RESULT_H))) != sizeof(I_RESULT_H)) {
		printLog(HEAD, "ERR: (%.18s)Socket write Fail(%d/%d)\n", header->productid, wlen, sizeof(I_RESULT_H)) ;
		return M_FAIL ;
	}
	printLog(HEAD, "SEND: (LEN:%d) (%.18s) I_RESULT_H-ERRCODE(%d) COUNT(%d) TOTAL(%d)\n", 
		wlen, header->productid, ntohl(i_result_h.error), ntohl(i_result_h.count), ntohl(i_result_h.total)) ;

	return ret ;
}
Esempio n. 24
0
void
watcher(void)
{
	Json *jv, *jtop;
	vlong id;
	char *text, *created_at, *user;
	char *buf;
	int fd, n, i;
	char fname[64];

	buf = malloc(BUFSIZ);
	if(buf == nil)
		sysfatal("malloc: %r");

	for(;;){
		fetch(fname);
		fd = open(fname, OREAD);
		n = readn(fd, buf, BUFSIZ);
		if(n <= 0){
			fprint(2, "read failed.\n");
			sleep(INTERVAL);
			continue;
		}
		/*print("(read %d bytes in %s)\n", n, fname);*/
		buf[n] = 0;

		jtop = parsejson(buf);
		if(jtop == nil){
			fprint(2, "parsejson failed.\n");
			sleep(INTERVAL);
			continue;
		}
		jv = jtop->value[0]; /* FIXME */

		for(i = jv->len - 1; i >= 0; i--){
			id = jint(jlookup(jv->value[i], "id"));
			if(id <= lastid)
				continue;
			text = jstring(jlookup(jv->value[i], "text"));
			created_at = jstring(jlookup(jv->value[i], "created_at"));
			user = jstring(jlookup(jv->value[i], "from_user"));
			print("[%s] %s (%s)\n", user, text, created_at);
			lastid = id;
		}

		jclose(jv);
		close(fd);
		sleep(INTERVAL);
	}
}
Esempio n. 25
0
const int SerialImpl::readWithControl(const int fd, char *buf, const int size)
{
	char	tmp[256];
	int		iTotSize	= size + 2;		// start(byte) + data(size) + end(byte)

	if (iTotSize != readn (fd, tmp, iTotSize)) {
		return (kuNOK);
	}

	// copies received data to user buffer
	memcpy (buf, tmp + 1, size);

	return (size);
}
Esempio n. 26
0
int main(void){
	while(scanf("%d",&n)!=EOF){
		first = 1, sign = '+';
		if(n<0) sign = '-',n/=-1;
		if(n) doprint(8);
		for(i = 0; i < 8; i++){
			readn(&n);
			if(n) doprint(7-i);
		}
		if(first) putchar('0');
		putchar('\n');
	}
	return 0;
}
Esempio n. 27
0
Packet *recvPkt(int sd) {
    Packet *pkt = NULL;

    pkt = (Packet*)calloc(1, sizeof(Packet));
    if(!pkt) {
        fprintf(stderr, "Can't calloc.\n");
        return NULL;
    }

    if(!readn(sd, (char*)&pkt->type, sizeof(pkt->type))) {
        free(pkt);
        return NULL;
    }

    if(!readn(sd, (char*)&pkt->len, sizeof(pkt->len))) {
        free(pkt);
        return NULL;
    }
    pkt->len = ntohl(pkt->len);

    if(pkt->len > 0) {
        pkt->text = (char*)malloc(pkt->len);
        if(!pkt->text) {
            fprintf(stderr, "Can't malloc.\n");
            free(pkt);
            return NULL;
        }

        if(!readn(sd, pkt->text, pkt->len)) {
            free(pkt);
            return NULL;
        }
    }

    //printf("recvPkt: type %d len %d text %s\n", pkt->type, pkt->len, pkt->text);
    return pkt;
}
Esempio n. 28
0
/* Function to run thread that receives packets from the tunnel,
   strips off the header, and sends the to the tap.  sockets should
   be a pointer to a socks_h structure holding the socket 
   file descriptors. */
void* incoming(void* sockets) {

  char msg[PAYLOAD_SIZE];
  ushort type, msg_length;
  int sent, sent_total;
  struct socks_h *socks = (struct socks_h*)sockets;

  while(1) {  // Loop forever

    // Get next header
    readn(socks->remote_sock, msg, HEADER_SIZE);

    // Get packet type and length
    type = ntohs(*(ushort*)msg);
    msg_length = ntohs(*(ushort*)(msg+TYPE_SIZE));
    printf("Received header from tunnel: type %x\tlength: %u \n", type, msg_length);
    
    // Get packet payload
    readn(socks->remote_sock, msg, msg_length);
    
    // Send payload to tap
    sent_total = 0;
    do { // Keep sending until entire payload has been sent
      if((sent = write(socks->tun_sock, msg+sent_total, msg_length - sent_total)) < 0) {
	perror("Incoming send");
	exit(EXIT_FAILURE);
      }
      sent_total += sent;
    } while(sent_total < msg_length);

    printf("Sent %d bytes to tap\n", sent_total);

  }
  printf("Exiting outgoing thread\n");

  return NULL;
}
Esempio n. 29
0
int
main(int argc, char **argv)
{
    int sd;
    int n;
    int toread;
    char writebuf[8192];
    char readbuf[1024 * 1024];
    char *str;

    sd = connect_to_server(DEFAULT_IPADDR, DEFAULT_PORT);
    assert(sd >= 0);

    str = "cas foo 0 0 3 1\r\nbar\r\n";
    printf("write: %4d: %s", strlen(str), str);
    n = write(sd, str, strlen(str));
    if (n < 0) {
        perror("write");
    }
    assert(n == strlen(str));

    n = read(sd, readbuf, 1);
    if (n < 0) {
        perror("read");
    }
    assert(n == 1);
    printf("read : %4d: %.*s", n, n, readbuf);

    if (readbuf[0] == 'S') {
        toread = strlen("STORED") + strlen("\r\n") - 1;
    } else if (readbuf[0] == 'E') {
        toread = strlen("EXISTS") + strlen("\r\n") - 1;
    } else if (readbuf[0] == 'N') {
        toread = strlen("NOT_FOUND") + strlen("\r\n") - 1;
    } else {
        assert(0);
    }

    n = readn(sd, readbuf, toread);
    if (n < 0) {
        perror("read");
    }
    assert(n > 0);
    printf("%.*s", n, readbuf);

    close(sd);

    return 0;
}
Esempio n. 30
0
void
threadmain(int argc, char *argv[])
{
	char *host;
	int dotrunc, n, type;
	uchar *p, score[VtScoreSize];
	VtConn *z;

	fmtinstall('F', vtfcallfmt);
	fmtinstall('V', vtscorefmt);

	host = nil;
	dotrunc = 0;
	type = VtDataType;
	ARGBEGIN{
	case 'z':
		dotrunc = 1;
		break;
	case 'h':
		host = EARGF(usage());
		break;
	case 't':
		type = atoi(EARGF(usage()));
		break;
	default:
		usage();
		break;
	}ARGEND

	if(argc != 0)
		usage();

	p = vtmallocz(VtMaxLumpSize+1);
	n = readn(0, p, VtMaxLumpSize+1);
	if(n > VtMaxLumpSize)
		sysfatal("input too big: max block size is %d", VtMaxLumpSize);
	z = vtdial(host);
	if(z == nil)
		sysfatal("could not connect to server: %r");
	if(vtconnect(z) < 0)
		sysfatal("vtconnect: %r");
	if(dotrunc)
		n = vtzerotruncate(type, p, n);
	if(vtwrite(z, score, type, p, n) < 0)
		sysfatal("vtwrite: %r");
	vthangup(z);
	print("%V\n", score);
	threadexitsall(0);
}