示例#1
0
ssize_t tls_prng_dev_read(TLS_PRNG_SRC *dev, size_t len)
{
    const char *myname = "tls_prng_dev_read";
    unsigned char buffer[UCHAR_MAX];
    ssize_t count;
    size_t  rand_bytes;

    if (len <= 0)
	msg_panic("%s: bad read length: %ld", myname, (long) len);

    if (len > sizeof(buffer))
	rand_bytes = sizeof(buffer);
    else
	rand_bytes = len;
    errno = 0;
#ifdef __APPLE_OS_X_SERVER__
    const char *p_no_poll = "apple-no-poll";
    count = timed_read(dev->fd, buffer, rand_bytes, dev->timeout, (void *)p_no_poll);
#else /* __APPLE_OS_X_SERVER__ */
    count = timed_read(dev->fd, buffer, rand_bytes, dev->timeout, (void *) 0);
#endif /* __APPLE_OS_X_SERVER__ */
    if (count > 0) {
	if (msg_verbose)
	    msg_info("%s: read %ld bytes from entropy device %s",
		     myname, (long) count, dev->name);
	RAND_seed(buffer, count);
    } else {
	if (msg_verbose)
	    msg_info("%s: cannot read %ld bytes from entropy device %s: %m",
		     myname, (long) rand_bytes, dev->name);
    }
    return (count);
}
示例#2
0
文件: popen.c 项目: wazhang/codebase
TEST(TIMEDREAD, CASE1)
{
	char result[4096];
	ASSERT_EQ(1, timed_read("aaa", result, 4096));
	EXPECT_EQ(-1, timed_read("aaabbbb", result, 4096));
	EXPECT_EQ(-1, timed_read("ls", result, 4096));
	EXPECT_STREQ("a",result);
	
}
示例#3
0
文件: kweb.c 项目: klueska/kweb
static int extract_request(struct http_connection *c,
                           struct http_request *r)
{
    int ret = 0;
    while(1) {
        /* Parse a request header from the connection buf. */
        parse_request_header(r, c->buf, c->buf_length);

        /* If we found one, extract the rest of the request based on the length,
         * and return to process it. */
        int len = r->length;
        if(len > 0) {
            /* Prepare r->buf to receive the extracted request. */
            if (len > sizeof(r->static_buf))
                r->buf = malloc(len);

            /* If the length is <= the size of the connection buffer, we can just
             * copy it out into the request buffer, and we are done. */
            if (len <= c->buf_length) {
                memcpy(r->buf, c->buf, len);
                c->buf_length = c->buf_length - len;
                memmove(c->buf, &c->buf[len], c->buf_length);
                /* Otherwise, we need to read in the rest of the request from the wire. */
            } else {
                memcpy(r->buf, c->buf, c->buf_length);
                len -= c->buf_length;
                c->buf_length = 0;
                while (len) {
                    ret = timed_read(c, &r->buf[r->length - len], len);
                    len -= ret;
                    if(ret <= 0)
                        return ret;
                }
                return r->length;
            }

            /* Honor some non-persistent clients */
            if (strstr(r->buf, "Connection: close"))
                c->should_close = 1;

            return len;
        }

        /* Otherwise, try and read in the next request from the socket */
        ret = timed_read(c, &c->buf[c->buf_length], sizeof(c->buf) - c->buf_length);

        /* If the return code is invalid or marks the end of a connection, just
         * return it. */
        if(ret <= 0)
            return ret;

        /* Otherwise, update the buf_length and loop back around to try and
         * extract the request again. */
        c->buf_length += ret;
    }
}
示例#4
0
ssize_t tls_prng_file_read(TLS_PRNG_SRC *fh, size_t len)
{
    const char *myname = "tls_prng_file_read";
    char    buffer[8192];
    ssize_t to_read;
    ssize_t count;

    if (msg_verbose)
	msg_info("%s: seed internal pool from file %s", myname, fh->name);

    if (lseek(fh->fd, 0, SEEK_SET) < 0) {
	if (msg_verbose)
	    msg_info("cannot seek entropy file %s: %m", fh->name);
	return (-1);
    }
    errno = 0;
    for (to_read = len; to_read > 0; to_read -= count) {
	if ((count = timed_read(fh->fd, buffer, to_read > sizeof(buffer) ?
				sizeof(buffer) : to_read,
				fh->timeout, (void *) 0)) < 0) {
	    if (msg_verbose)
		msg_info("cannot read entropy file %s: %m", fh->name);
	    return (-1);
	}
	if (count == 0)
	    break;
	RAND_seed(buffer, count);
    }
    if (msg_verbose)
	msg_info("read %ld bytes from entropy file %s: %m",
		 (long) (len - to_read), fh->name);
    return (len - to_read);
}
示例#5
0
文件: popen.c 项目: wazhang/codebase
int main(int argc, char **argv) {
        char result[4096];
	::testing::InitGoogleTest(&argc, argv);
	RUN_ALL_TESTS();
	printf("*****\n");
        timed_read("/usr/bin/ls", result, 4096);
	printf("%s\n", result);
}
示例#6
0
/*
 * Write one byte to an empty fifo, then try to read one byte and make sure
 * we don't get back EAGAIN.
 */
static void
test_nonblocking_one_byte(void)
{
	int reader_fd, ret, timedout, writer_fd;
	ssize_t len;
	u_char ch;

	makefifo("testfifo", __func__);
	if (openfifo("testfifo", __func__, &reader_fd, &writer_fd)
	    < 0) {
		warn("test_nonblocking: openfifo: testfifo");
		cleanfifo2("testfifo", -1, -1);
		exit(-1);
	}

	if (set_nonblocking(reader_fd, __func__) < 0) {
		cleanfifo2("testfifo", reader_fd, writer_fd);
		exit(-1);
	}

	ch = 0xfe;
	ret = timed_write(writer_fd, &ch, sizeof(ch), &len, 5, &timedout,
	    __func__);
	if (ret < 0) {
		warn("test_nonblocking_one_byte: timed_write");
		cleanfifo2("testfifo", reader_fd, writer_fd);
		exit(-1);
	}
	if (len != sizeof(ch)) {
		warnx("test_nonblocking_one_byte: timed_write: tried to write "
		    "%zu, wrote %zd", sizeof(ch), len);
		cleanfifo2("testfifo", reader_fd, writer_fd);
		exit(-1);
	}

	ch = 0xab;
	ret = timed_read(reader_fd, &ch, sizeof(ch), &len, 5, &timedout,
	    __func__);
	if (ret < 0) {
		warn("test_nonblocking_one_byte: timed_read");
		cleanfifo2("testfifo", reader_fd, writer_fd);
		exit(-1);
	}
	if (len != sizeof(ch)) {
		warnx("test_nonblocking_one_byte: timed_read: wanted %zu, read "
		    "%zd", sizeof(ch), len);
		cleanfifo2("testfifo", reader_fd, writer_fd);
		exit(-1);
	}
	if (ch != 0xfe) {
		warnx("test_nonblocking_one_byte: timed_read: expected to read "
		    "0x%02x, read 0x%02x", 0xfe, ch);
		cleanfifo2("testfifo", reader_fd, writer_fd);
		exit(-1);
	}

	cleanfifo2("testfifo", reader_fd, writer_fd);
}
示例#7
0
ssize_t tls_prng_egd_read(TLS_PRNG_SRC *egd, size_t len)
{
    const char *myname = "tls_prng_egd_read";
    unsigned char buffer[UCHAR_MAX];
    ssize_t count;

    if (len <= 0)
	msg_panic("%s: bad length %ld", myname, (long) len);

    buffer[0] = 1;
    buffer[1] = (len > UCHAR_MAX ? UCHAR_MAX : len);

    if (timed_write(egd->fd, buffer, 2, egd->timeout, (void *) 0) != 2) {
	msg_info("cannot write to EGD server %s: %m", egd->name);
	return (-1);
    }
    if (timed_read(egd->fd, buffer, 1, egd->timeout, (void *) 0) != 1) {
	msg_info("cannot read from EGD server %s: %m", egd->name);
	return (-1);
    }
    count = buffer[0];
    if (count > sizeof(buffer))
	count = sizeof(buffer);
    if (count == 0) {
	msg_info("EGD server %s reports zero bytes available", egd->name);
	return (-1);
    }
    if (timed_read(egd->fd, buffer, count, egd->timeout, (void *) 0) != count) {
	msg_info("cannot read %ld bytes from EGD server %s: %m",
		 (long) count, egd->name);
	return (-1);
    }
    if (msg_verbose)
	msg_info("%s: got %ld bytes from EGD server %s", myname,
		 (long) count, egd->name);
    RAND_seed(buffer, count);
    return (count);
}
示例#8
0
int Socket::receive( unsigned char *inBuffer, int inNumBytes,
	long inTimeout ) {
    if( mIsConnectionBroken ) return -1;
	
	int *socketIDptr = (int *)( mNativeObjectPointer );
	int socketID = socketIDptr[0];
	
	if( inTimeout == -1 ) {
        // use MSG_WAITALL flag here to block until inNumBytes has arrived
		return recv( socketID, inBuffer, inNumBytes, MSG_WAITALL );
		}
	else {		
		return timed_read( socketID, inBuffer, inNumBytes, inTimeout );
		}
	}
示例#9
0
int     master_monitor(int time_limit)
{
    pid_t   pid;
    int     pipes[2];
    char    buf[1];

    /*
     * Sanity check.
     */
    if (time_limit <= 0)
	msg_panic("master_monitor: bad time limit: %d", time_limit);

    /*
     * Set up the plumbing for child-to-parent communication.
     */
    if (pipe(pipes) < 0)
	msg_fatal("pipe: %m");
    close_on_exec(pipes[0], CLOSE_ON_EXEC);
    close_on_exec(pipes[1], CLOSE_ON_EXEC);

    /*
     * Fork the child, and wait for it to report successful initialization.
     */
    switch (pid = fork()) {
    case -1:
	/* Error. */
	msg_fatal("fork: %m");
    case 0:
	/* Child. Initialize as daemon in the background. */
	close(pipes[0]);
	return (pipes[1]);
    default:
	/* Parent. Monitor the child in the foreground. */
	close(pipes[1]);
	switch (timed_read(pipes[0], buf, 1, time_limit, (char *) 0)) {
	default:
	    /* The child process still runs, but something is wrong. */
	    (void) kill(pid, SIGKILL);
	    /* FALLTHROUGH */
	case 0:
	    /* The child process exited prematurely. */
	    msg_fatal("daemon initialization failure");
	case 1:
	    /* The child process initialized successfully. */
	    exit(0);
	}
    }
}
示例#10
0
文件: client.c 项目: kvap/raft
static bool try_query(Message *msg, Message *answer, timeout_t *timeout) {
	int s = get_connection(timeout);
	if (s < 0) return false;

	if (timeout_happened(timeout)) {
		debug("try_query: get_connection() timed out\n");
		return false;
	}

	if (!timed_write(s, msg, sizeof(Message), timeout)) {
		debug("try_query: failed to send the query to the leader\n");
		return false;
	}

	if (!timed_read(s, answer, sizeof(Message), timeout)) {
		debug("try_query: failed to recv the answer from the leader\n");
		return false;
	}

	return true;
}
示例#11
0
//********************************************************************************
// Function: redirect_count
//
// Description: Recieve Control Plane redirect count.
//********************************************************************************
static int32_t redirect_count(void)
{
    void *context = zmq_ctx_new ();
    void *requester = zmq_socket(context, ZMQ_REQ);

    int32_t timeo{};
    zmq_setsockopt(requester, ZMQ_LINGER, (void*) &timeo, sizeof(timeo));

    char buffer[64];
    sprintf(buffer, "tcp://localhost:%d", TCPLANE_SERVICE);
    zmq_connect(requester, buffer);

    sprintf(buffer, "%d", redirectCount);
    zmq_send(requester, buffer, strlen(buffer), 0);

    size_t size = timed_read(requester, buffer, sizeof(buffer), READ_TIMEOUT);
    if(size)
        size = atoi(buffer);    
    zmq_close(requester);
    zmq_ctx_destroy(context);
    return size;
}
示例#12
0
文件: fifo_io.c 项目: coyizumi/cs111
/*
 * This test operates on blocking and non-blocking fifo file descriptors, in
 * order to determine whether they block at good moments or not.  By good we
 * mean: don't block for non-blocking sockets, and do block for blocking
 * ones, assuming there isn't I/O buffer to satisfy the request.
 *
 * We use a timeout of 5 seconds, concluding that in 5 seconds either all I/O
 * that can take place will, and that if we reach the end of the timeout,
 * then blocking has occurred.
 *
 * We assume that the buffer size on a fifo is <512K, and as such, that
 * writing that much data without an active reader will result in blocking.
 */
static void
test_blocking_read_empty(void)
{
    int reader_fd, ret, timedout, writer_fd;
    ssize_t len;
    u_char ch;

    makefifo("testfifo", __func__);
    if (openfifo("testfifo", &reader_fd, &writer_fd)
            < 0) {
        warn("test_blocking_read_empty: openfifo: testfifo");
        cleanfifo2("testfifo", -1, -1);
        exit(-1);
    }

    /*
     * Read one byte from an empty blocking fifo, block as there is no
     * data.
     */
    if (set_blocking(reader_fd, __func__) < 0) {
        cleanfifo2("testfifo", reader_fd, writer_fd);
        exit(-1);
    }

    ret = timed_read(reader_fd, &ch, sizeof(ch), &len, 5, &timedout,
                     __func__);
    if (ret != -1) {
        warnx("test_blocking_read_empty: timed_read: returned "
              "success");
        cleanfifo2("testfifo", reader_fd, writer_fd);
        exit(-1);
    }
    if (errno != EINTR) {
        warn("test_blocking_read_empty: timed_read");
        cleanfifo2("testfifo", reader_fd, writer_fd);
        exit(-1);
    }

    /*
     * Read one byte from an empty non-blocking fifo, return EAGAIN as
     * there is no data.
     */
    if (set_nonblocking(reader_fd, __func__) < 0) {
        cleanfifo2("testfifo", reader_fd, writer_fd);
        exit(-1);
    }

    ret = timed_read(reader_fd, &ch, sizeof(ch), &len, 5, &timedout,
                     __func__);
    if (ret != -1) {
        warnx("test_blocking_read_empty: timed_read: returned "
              "success");
        cleanfifo2("testfifo", reader_fd, writer_fd);
        exit(-1);
    }
    if (errno != EAGAIN) {
        warn("test_blocking_read_empty: timed_read");
        cleanfifo2("testfifo", reader_fd, writer_fd);
        exit(-1);
    }

    cleanfifo2("testfifo", reader_fd, writer_fd);
}
示例#13
0
static int NBScat_exec(struct ast_channel *chan, const char *data)
{
	int res=0;
	int fds[2];
	int ms = -1;
	int pid = -1;
	struct ast_format owriteformat;
	struct timeval next;
	struct ast_frame *f;
	struct myframe {
		struct ast_frame f;
		char offset[AST_FRIENDLY_OFFSET];
		short frdata[160];
	} myf;

	ast_format_clear(&owriteformat);
	if (socketpair(AF_LOCAL, SOCK_STREAM, 0, fds)) {
		ast_log(LOG_WARNING, "Unable to create socketpair\n");
		return -1;
	}
	
	ast_stopstream(chan);

	ast_format_copy(&owriteformat, &chan->writeformat);
	res = ast_set_write_format_by_id(chan, AST_FORMAT_SLINEAR);
	if (res < 0) {
		ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
		return -1;
	}
	
	res = NBScatplay(fds[1]);
	/* Wait 1000 ms first */
	next = ast_tvnow();
	next.tv_sec += 1;
	if (res >= 0) {
		pid = res;
		/* Order is important -- there's almost always going to be mp3...  we want to prioritize the
		   user */
		for (;;) {
			ms = ast_tvdiff_ms(next, ast_tvnow());
			if (ms <= 0) {
				res = timed_read(fds[0], myf.frdata, sizeof(myf.frdata));
				if (res > 0) {
					myf.f.frametype = AST_FRAME_VOICE;
					ast_format_set(&myf.f.subclass.format, AST_FORMAT_SLINEAR, 0);
					myf.f.datalen = res;
					myf.f.samples = res / 2;
					myf.f.mallocd = 0;
					myf.f.offset = AST_FRIENDLY_OFFSET;
					myf.f.src = __PRETTY_FUNCTION__;
					myf.f.delivery.tv_sec = 0;
					myf.f.delivery.tv_usec = 0;
					myf.f.data.ptr = myf.frdata;
					if (ast_write(chan, &myf.f) < 0) {
						res = -1;
						break;
					}
				} else {
					ast_debug(1, "No more mp3\n");
					res = 0;
					break;
				}
				next = ast_tvadd(next, ast_samp2tv(myf.f.samples, 8000));
			} else {
				ms = ast_waitfor(chan, ms);
				if (ms < 0) {
					ast_debug(1, "Hangup detected\n");
					res = -1;
					break;
				}
				if (ms) {
					f = ast_read(chan);
					if (!f) {
						ast_debug(1, "Null frame == hangup() detected\n");
						res = -1;
						break;
					}
					if (f->frametype == AST_FRAME_DTMF) {
						ast_debug(1, "User pressed a key\n");
						ast_frfree(f);
						res = 0;
						break;
					}
					ast_frfree(f);
				} 
			}
		}
	}
	close(fds[0]);
	close(fds[1]);
	
	if (pid > -1)
		kill(pid, SIGKILL);
	if (!res && owriteformat.id)
		ast_set_write_format(chan, &owriteformat);

	return res;
}
示例#14
0
static int pipe_exec(struct cw_channel *chan, int argc, char **argv)
{
	int res=0;
	struct localuser *u;
	int fds[2];
	int ms = -1;
	int pid = -1;
	int owriteformat;
	int oreadformat;
	int timeout = 2000;
	struct timeval last;
	struct cw_frame *f;
	struct myframe {
		struct cw_frame f;
		char offset[CW_FRIENDLY_OFFSET];
		short frdata[160];
	} myf;

	last.tv_usec = 0;
	last.tv_sec = 0;

	if (argc < 2 || argc > 3) {
		cw_log(LOG_ERROR, "Syntax: %s\n", pipe_syntax);
		return -1;
	}

	LOCAL_USER_ADD(u);

	if (pipe(fds)) {
		cw_log(LOG_WARNING, "Unable to create pipe\n");
		LOCAL_USER_REMOVE(u);
		return -1;
	}

// MOC: Setting non blocking doesn't seem to change anything
//	flags = fcntl(fds[1], F_GETFL);
//	fcntl(fds[1], F_SETFL, flags | O_NONBLOCK);

//	flags = fcntl(fds[0], F_GETFL);
//	fcntl(fds[0], F_SETFL, flags | O_NONBLOCK);

	cw_stopstream(chan);

	if (chan->_state != CW_STATE_UP)
		res = cw_answer(chan);
		
	if (res) {
		close(fds[0]);
		close(fds[1]);
		cw_log(LOG_WARNING, "Answer failed!\n");
		LOCAL_USER_REMOVE(u);
		return -1;
	}

	oreadformat = chan->readformat;
	res = cw_set_read_format(chan, CW_FORMAT_SLINEAR);

	owriteformat = chan->writeformat;
	res += cw_set_write_format(chan, CW_FORMAT_SLINEAR);

	if (res < 0) {
		close(fds[0]);
		close(fds[1]);
		cw_log(LOG_WARNING, "Unable to set write format to signed linear\n");
		LOCAL_USER_REMOVE(u);
		return -1;
	}

	res = pipeencode(argv[1], argv[2], fds[0], fds[1]);

	if (res >= 0) {
	   last = cw_tvnow();
	   last.tv_sec += 1;

		pid = res;
		for (;;) {
			/* Wait for audio, and stream */
			if (argv[0][0] == '0') {
				/* START WRITE TO FD */
				ms = cw_waitfor(chan, 10);
				if (ms < 0) {
					cw_log(LOG_DEBUG, "Hangup detected\n");
					res = -1;
					break;
				} else if (ms > 0) {
					f = cw_read(chan);
					if (!f) {
						cw_log(LOG_DEBUG, "Null frame == hangup() detected\n");
						res = -1;
						break;
					}
					if (f->frametype == CW_FRAME_DTMF) {
						cw_log(LOG_DEBUG, "User pressed a key\n");
						cw_fr_free(f);
						res = 0;
						break;
					}
					if (f->frametype == CW_FRAME_VOICE) {
						res = write(fds[1], f->data, f->datalen);
						if (res < 0) {
							if (errno != EAGAIN) {
								cw_log(LOG_WARNING, "Write failed to pipe: %s\n", strerror(errno));
                                cw_fr_free(f);
								res = -1;
								break;
							}
						}
					}
					cw_fr_free(f);
				} /* END WRITE TO FD */
			} else {
				/* START WRITE CHANNEL */
				ms = cw_tvdiff_ms(last, cw_tvnow());
				if (ms <= 0) {
					res = timed_read(fds[0], myf.frdata, sizeof(myf.frdata), timeout);
					if (res > 0) {
                        cw_fr_init_ex(&myf.f, CW_FRAME_VOICE, CW_FORMAT_SLINEAR, __PRETTY_FUNCTION__);
						myf.f.datalen = res;
						myf.f.samples = res/sizeof(int16_t);
						myf.f.offset = CW_FRIENDLY_OFFSET;
						myf.f.data = myf.frdata;
						if (cw_write(chan, &myf.f) < 0)
                        {
							res = -1;
							break;
						}
					} else {
						cw_log(LOG_DEBUG, "No more stream\n");
						res = 0;
						break;
					}
					last = cw_tvadd(last, cw_samp2tv(myf.f.samples, 8000));
				} else {
					ms = cw_waitfor(chan, ms);
					if (ms < 0) {
						cw_log(LOG_DEBUG, "Hangup detected\n");
						res = -1;
						break;
					}
					if (ms) {
						f = cw_read(chan);
						if (!f) {
							cw_log(LOG_DEBUG, "Null frame == hangup() detected\n");
							res = -1;
							break;
						}
						if (f->frametype == CW_FRAME_DTMF) {
							cw_log(LOG_DEBUG, "User pressed a key\n");
							cw_fr_free(f);
							res = 0;
							break;
						}
						cw_fr_free(f);
					}
				}
				/* END WRITE CHANNEL */
			}
		}
	}
	close(fds[0]);
	close(fds[1]);

	LOCAL_USER_REMOVE(u);
	if (pid > -1)
		kill(pid, SIGKILL);
	if (!res && oreadformat)
		cw_set_read_format(chan, oreadformat);
	if (!res && owriteformat)
		cw_set_write_format(chan, owriteformat);

	return res;
}
示例#15
0
文件: app_mp3.c 项目: KaloNK/asterisk
static int mp3_exec(struct ast_channel *chan, const char *data)
{
	int res=0;
	int fds[2];
	int ms = -1;
	int pid = -1;
	RAII_VAR(struct ast_format *, owriteformat, NULL, ao2_cleanup);
	int timeout = 2000;
	struct timeval next;
	struct ast_frame *f;
	struct myframe {
		struct ast_frame f;
		char offset[AST_FRIENDLY_OFFSET];
		short frdata[160];
	} myf = {
		.f = { 0, },
	};
	struct ast_format * native_format;
	unsigned int sampling_rate;
	struct ast_format * write_format;

	if (ast_strlen_zero(data)) {
		ast_log(LOG_WARNING, "MP3 Playback requires an argument (filename)\n");
		return -1;
	}

	if (pipe(fds)) {
		ast_log(LOG_WARNING, "Unable to create pipe\n");
		return -1;
	}
	
	ast_stopstream(chan);

	native_format = ast_format_cap_get_format(ast_channel_nativeformats(chan), 0);
	sampling_rate = ast_format_get_sample_rate(native_format);
	write_format = ast_format_cache_get_slin_by_rate(sampling_rate);

	owriteformat = ao2_bump(ast_channel_writeformat(chan));
	res = ast_set_write_format(chan, write_format);
	if (res < 0) {
		ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
		return -1;
	}

	myf.f.frametype = AST_FRAME_VOICE;
	myf.f.subclass.format = write_format;
	myf.f.mallocd = 0;
	myf.f.offset = AST_FRIENDLY_OFFSET;
	myf.f.src = __PRETTY_FUNCTION__;
	myf.f.delivery.tv_sec = 0;
	myf.f.delivery.tv_usec = 0;
	myf.f.data.ptr = myf.frdata;
	
	res = mp3play(data, sampling_rate, fds[1]);
	if (!strncasecmp(data, "http://", 7)) {
		timeout = 10000;
	}
	/* Wait 1000 ms first */
	next = ast_tvnow();
	next.tv_sec += 1;
	if (res >= 0) {
		pid = res;
		/* Order is important -- there's almost always going to be mp3...  we want to prioritize the
		   user */
		for (;;) {
			ms = ast_tvdiff_ms(next, ast_tvnow());
			if (ms <= 0) {
				res = timed_read(fds[0], myf.frdata, sizeof(myf.frdata), timeout);
				if (res > 0) {
					myf.f.datalen = res;
					myf.f.samples = res / 2;
					if (ast_write(chan, &myf.f) < 0) {
						res = -1;
						break;
					}
				} else {
					ast_debug(1, "No more mp3\n");
					res = 0;
					break;
				}
				next = ast_tvadd(next, ast_samp2tv(myf.f.samples, sampling_rate));
			} else {
				ms = ast_waitfor(chan, ms);
				if (ms < 0) {
					ast_debug(1, "Hangup detected\n");
					res = -1;
					break;
				}
				if (ms) {
					f = ast_read(chan);
					if (!f) {
						ast_debug(1, "Null frame == hangup() detected\n");
						res = -1;
						break;
					}
					if (f->frametype == AST_FRAME_DTMF) {
						ast_debug(1, "User pressed a key\n");
						ast_frfree(f);
						res = 0;
						break;
					}
					ast_frfree(f);
				} 
			}
		}
	}
	close(fds[0]);
	close(fds[1]);
	
	if (pid > -1)
		kill(pid, SIGKILL);
	if (!res && owriteformat)
		ast_set_write_format(chan, owriteformat);

	ast_frfree(&myf.f);
	
	return res;
}
示例#16
0
static int mp3_exec(struct ast_channel *chan, void *data)
{
	int res=0;
	struct localuser *u;
	int fds[2];
	int ms = -1;
	int pid = -1;
	int owriteformat;
	int timeout = 2000;
	struct timeval next;
	struct ast_frame *f;
	struct myframe {
		struct ast_frame f;
		char offset[AST_FRIENDLY_OFFSET];
		short frdata[160];
	} myf;
	
	if (ast_strlen_zero(data)) {
		ast_log(LOG_WARNING, "MP3 Playback requires an argument (filename)\n");
		return -1;
	}

	LOCAL_USER_ADD(u);

	if (pipe(fds)) {
		ast_log(LOG_WARNING, "Unable to create pipe\n");
		LOCAL_USER_REMOVE(u);
		return -1;
	}
	
	ast_stopstream(chan);

	owriteformat = chan->writeformat;
	res = ast_set_write_format(chan, AST_FORMAT_SLINEAR);
	if (res < 0) {
		ast_log(LOG_WARNING, "Unable to set write format to signed linear\n");
		LOCAL_USER_REMOVE(u);
		return -1;
	}
	
	res = mp3play((char *)data, fds[1]);
	if (!strncasecmp((char *)data, "http://", 7)) {
		timeout = 10000;
	}
	/* Wait 1000 ms first */
	next = ast_tvnow();
	next.tv_sec += 1;
	if (res >= 0) {
		pid = res;
		/* Order is important -- there's almost always going to be mp3...  we want to prioritize the
		   user */
		for (;;) {
			ms = ast_tvdiff_ms(next, ast_tvnow());
			if (ms <= 0) {
				res = timed_read(fds[0], myf.frdata, sizeof(myf.frdata), timeout);
				if (res > 0) {
					myf.f.frametype = AST_FRAME_VOICE;
					myf.f.subclass = AST_FORMAT_SLINEAR;
					myf.f.datalen = res;
					myf.f.samples = res / 2;
					myf.f.mallocd = 0;
					myf.f.offset = AST_FRIENDLY_OFFSET;
					myf.f.src = __PRETTY_FUNCTION__;
					myf.f.delivery.tv_sec = 0;
					myf.f.delivery.tv_usec = 0;
					myf.f.data = myf.frdata;
					if (ast_write(chan, &myf.f) < 0) {
						res = -1;
						break;
					}
				} else {
					ast_log(LOG_DEBUG, "No more mp3\n");
					res = 0;
					break;
				}
				next = ast_tvadd(next, ast_samp2tv(myf.f.samples, 8000));
			} else {
				ms = ast_waitfor(chan, ms);
				if (ms < 0) {
					ast_log(LOG_DEBUG, "Hangup detected\n");
					res = -1;
					break;
				}
				if (ms) {
					f = ast_read(chan);
					if (!f) {
						ast_log(LOG_DEBUG, "Null frame == hangup() detected\n");
						res = -1;
						break;
					}
					if (f->frametype == AST_FRAME_DTMF) {
						ast_log(LOG_DEBUG, "User pressed a key\n");
						ast_frfree(f);
						res = 0;
						break;
					}
					ast_frfree(f);
				} 
			}
		}
	}
	close(fds[0]);
	close(fds[1]);
	
	if (pid > -1)
		kill(pid, SIGKILL);
	if (!res && owriteformat)
		ast_set_write_format(chan, owriteformat);

	LOCAL_USER_REMOVE(u);
	
	return res;
}
示例#17
0
int Socket::receive( unsigned char *inBuffer, int inNumBytes,
                     long inTimeout ) {

    unsigned int *socketIDptr = (unsigned int *)( mNativeObjectPointer );
    unsigned int socketID = socketIDptr[0];

    int numReceived = 0;

    char error = false;
    char errorReturnValue = -1;


    char stopLooping = false;


    // for win32, we can't specify MSG_WAITALL
    // so we have too loop until the entire message is received,
    // as long as there is no error.

    // note that if a timeout is set, we use the stopLooping flag
    // to return only the available data (we do not emulate MSG_WAITALL)

    while( numReceived < inNumBytes &&
            !error &&
            !stopLooping ) {

        // the number of bytes left to receive
        int numRemaining = inNumBytes - numReceived;

        // pointer to the spot in the buffer where the
        // remaining bytes should be stored
        unsigned char *remainingBuffer = &( inBuffer[ numReceived ] );

        int numReceivedIn;

        if( inTimeout == -1 ) {
            numReceivedIn =
                recv( socketID, (char*)remainingBuffer, numRemaining, 0 );
        }
        else {
            numReceivedIn =
                timed_read( socketID, remainingBuffer,
                            numRemaining, inTimeout );

            // stop looping after one timed read
            stopLooping = true;
        }


        if( numReceivedIn > 0 ) {
            numReceived += numReceivedIn;
        }
        else {
            if( numReceivedIn == 0 ) {
                // the socket was gracefully closed
                // return whatever we have received
                stopLooping = true;
            }
            else if( numReceivedIn == SOCKET_ERROR ) {
                error = true;
                // socket error
                errorReturnValue = -1;
            }
            else if( numReceivedIn == -2 ) {
                error = true;
                // timeout
                errorReturnValue = -2;
            }
            else {
                printf( "Unexpected return value from socket receive: %d.\n",
                        numReceivedIn );
                error = true;
                errorReturnValue = -1;
            }

        }

    }

    if( error ) {
        return errorReturnValue;
    }
    else {
        return numReceived;
    }
}
示例#18
0
static int recv_req(int fd, lscgid_t *cgi_req, int timeout)
{

    time_t          begin;
    time_t          cur;
    int             ret;

    begin = time(NULL);
    cgi_req->m_fdReceived = -1;
    ret = timed_read(fd, (char *)&cgi_req->m_data,
                     sizeof(lscgid_req), timeout - 1);
    if (ret == -1)
        return 500;
    ret = process_req_header(cgi_req);
    if (ret)
        return ret;
    //fprintf( stderr, "1 Proc: %ld, data: %ld\n", cgi_req->m_data.m_nproc.rlim_cur,
    //                        cgi_req->m_data.m_data.rlim_cur );

    if (cgi_req->m_data.m_type == LSCGID_TYPE_SUEXEC)
    {
        uint32_t pid = (uint32_t)getpid();
        write(STDOUT_FILENO, &pid, 4);
    }

    cur = time(NULL);
    timeout -= cur - begin;
    ret = timed_read(fd, cgi_req->m_pBuf,
                     cgi_req->m_data.m_szData, timeout);
    if (ret == -1)
        return 500;

    ret = process_req_data(cgi_req);
    if (ret)
    {
        s_pError = "lscgid: data error!";
        return ret;
    }
    if (cgi_req->m_data.m_type == LSCGID_TYPE_SUEXEC)
    {
        //cgi_req->m_fdReceived = recv_fd( fd );
        char nothing;
        if ((FDPass::readFd(fd, &nothing, 1, &cgi_req->m_fdReceived) == -1) ||
            (cgi_req->m_fdReceived == -1))
        {
            fprintf(stderr, "lscgid: read_fd() failed: %s\n",
                    strerror(errno));
            return 500;
        }
        if (cgi_req->m_fdReceived != STDIN_FILENO)
        {
            dup2(cgi_req->m_fdReceived, STDIN_FILENO);
            close(cgi_req->m_fdReceived);
            cgi_req->m_fdReceived = -1;
        }
    }
    //fprintf( stderr, "2 Proc: %ld, data: %ld\n", cgi_req->m_data.m_nproc.rlim_cur,
    //                        cgi_req->m_data.m_data.rlim_cur );
    return 0;

}
示例#19
0
static enum mad_flow input(void * data, struct mad_stream * stream) {
	static unsigned char buf[BUFSIZE + 1] = { 0 };
	struct stream * ptr = (struct stream *) data;

	static int nbyte = 0;
	int remnbyte = 0;

	if(feof(ptr->streamfd))
		return MAD_FLOW_STOP;

	if(stream->next_frame) {
		remnbyte = (unsigned) (& buf[nbyte] - stream->next_frame);
		memmove(buf, stream->next_frame, remnbyte);
	}

	if(ptr->preload) {
		nbyte = timed_read(fileno(ptr->streamfd), buf + remnbyte, BUFSIZE - remnbyte, ptr->timeout);

		if(nbyte == -1) {
			fputs("Stream timed out.\n", stderr);
		}

		else if(ptr->dump)
			fwrite(buf + remnbyte, sizeof(buf[0]), nbyte, ptr->dump);
	}
	else {
		while(nbyte < BUFSIZE) {
			int retval = timed_read(fileno(ptr->streamfd), buf + nbyte, BUFSIZE - nbyte, ptr->timeout);

			if(retval <= 0)
				break;

			if(ptr->dump)
				fwrite(buf + nbyte, sizeof(buf[0]), retval, ptr->dump);

			nbyte += retval;
		}

		if(!nbyte) {
			fputs("Stream timed out while trying to preload data.\n", stderr);
		}

		ptr->preload = !0;
	}
	
	if(nbyte <= 0)
		return MAD_FLOW_STOP;

	nbyte += remnbyte;

	mad_stream_buffer(stream, (unsigned char *) buf, nbyte);


	if(kill(ptr->parent, 0) == -1 && errno == ESRCH) {
		fclose(ptr->streamfd);
		killed = !0;
		return MAD_FLOW_STOP;
	}

	if(killed)
		return MAD_FLOW_STOP;

	return MAD_FLOW_CONTINUE;
}
示例#20
0
文件: parse.c 项目: bingos/bitrig
/* Parse, a-la IPv6 */
int
parse6(int fd, struct sockaddr_in6 *laddr, struct sockaddr_in6 *faddr)
{
	char	token[21], buf[BUFSIZ], *p;
	struct	sockaddr_in6 laddr2, faddr2;
	struct	passwd *pw;
	uid_t	uid;
	int	n;

	if (debug_flag && syslog_flag)
		syslog(LOG_DEBUG, "In function parse6(), from %s to %s",
		    gethost6(faddr), gethost6(laddr));

	faddr2 = *faddr;
	laddr2 = *laddr;
	lport = fport = 0;

	/* Read query from client */
	if ((n = timed_read(fd, buf, sizeof(buf) - 1, IO_TIMEOUT)) <= 0) {
		if (syslog_flag)
			syslog(LOG_NOTICE,
			    n ? "read from %s: %m" : "read from %s: EOF",
			    gethost6(faddr));
		if ((n = snprintf(buf, sizeof(buf),
		    "%d , %d : ERROR : UNKNOWN-ERROR\r\n", lport, fport))
		    >= sizeof(buf) || n < 0)
			n = strlen(buf);
		if (timed_write(fd, buf, n, IO_TIMEOUT) != n && syslog_flag) {
			syslog(LOG_NOTICE, "write to %s: %m", gethost6(faddr));
			return 1;
		}
		return 0;
	}
	buf[n] = '\0';

	/* Pull out local and remote ports */
	p = buf;
	while (isspace(*p))
		p++;
	if ((p = strtok(p, " \t,"))) {
		lport = atoi(p);
		if ((p = strtok(NULL, " \t,")))
			fport = atoi(p);
	}

	if (lport < 1 || lport > 65535 || fport < 1 || fport > 65535) {
		if (syslog_flag)
			syslog(LOG_NOTICE,
			    "scanf: invalid-port(s): %d , %d from %s",
			    lport, fport, gethost6(faddr));
		if ((n = snprintf(buf, sizeof(buf), "%d , %d : ERROR : %s\r\n",
		    lport, fport, unknown_flag ? "UNKNOWN-ERROR" :
		    "INVALID-PORT")) >= sizeof(buf) || n < 0)
			n = strlen(buf);
		if (timed_write(fd, buf, n, IO_TIMEOUT) != n && syslog_flag) {
			syslog(LOG_NOTICE, "write to %s: %m", gethost6(faddr));
			return 1;
		}
		return 0;
	}
	if (syslog_flag && verbose_flag)
		syslog(LOG_NOTICE, "request for (%d,%d) from %s",
		    lport, fport, gethost6(faddr));

	if (debug_flag && syslog_flag)
		syslog(LOG_DEBUG, "  After fscanf(), before k_getuid6()");

	/*
	 * Next - get the specific TCP connection and return the
	 * uid - user number.
	 */
	if (k_getuid6(&faddr2, htons(fport), laddr, htons(lport), &uid) == -1) {
		if (no_user_token_flag) {
			gentoken(token, sizeof token);
			syslog(LOG_NOTICE, "token %s == NO USER", token);
			if ((n = snprintf(buf, sizeof(buf),
			    "%d , %d : USERID : %s%s%s :%s\r\n", lport, fport,
			    opsys_name, charset_sep, charset_name, token))
			    >= sizeof(buf) || n < 0)
				n = strlen(buf);
			if (timed_write(fd, buf, n, IO_TIMEOUT) != n &&
			    syslog_flag) {
				syslog(LOG_NOTICE, "write to %s: %m",
				    gethost6(faddr));
				return 1;
			}
			return 0;
		}
		if (syslog_flag)
			syslog(LOG_DEBUG, "Returning: %d , %d : NO-USER",
			    lport, fport);
		if ((n = snprintf(buf, sizeof(buf), "%d , %d : ERROR : %s\r\n",
		    lport, fport, unknown_flag ? "UNKNOWN-ERROR" : "NO-USER"))
		    >= sizeof(buf) || n < 0)
			n = strlen(buf);
		if (timed_write(fd, buf, n, IO_TIMEOUT) != n && syslog_flag) {
			syslog(LOG_NOTICE, "write to %s: %m", gethost6(faddr));
			return 1;
		}
		return 0;
	}
	if (debug_flag && syslog_flag)
		syslog(LOG_DEBUG, "  After k_getuid6(), before getpwuid()");

	pw = getpwuid(uid);
	if (!pw) {
		if (syslog_flag)
			syslog(LOG_WARNING,
			    "getpwuid() could not map uid (%u) to name",
			    uid);
		if ((n = snprintf(buf, sizeof(buf),
		    "%d , %d : USERID : %s%s%s :%u\r\n",
		    lport, fport, opsys_name, charset_sep, charset_name, uid))
		    >= sizeof(buf) || n < 0)
			n = strlen(buf);
		if (timed_write(fd, buf, n, IO_TIMEOUT) != n && syslog_flag) {
			syslog(LOG_NOTICE, "write to %s: %m", gethost6(faddr));
			return 1;
		}
		return 0;
	}

	if (syslog_flag)
		syslog(LOG_DEBUG, "Successful lookup: %d , %d : %s",
		    lport, fport, pw->pw_name);

	if (noident_flag && check_noident(pw->pw_dir)) {
		if (syslog_flag && verbose_flag)
			syslog(LOG_NOTICE,
			    "user %s requested HIDDEN-USER for host %s: %d, %d",
			    pw->pw_name, gethost6(faddr), lport, fport);
		if ((n = snprintf(buf, sizeof(buf),
		    "%d , %d : ERROR : HIDDEN-USER\r\n", lport, fport))
		    >= sizeof(buf) || n < 0)
			n = strlen(buf);
		if (timed_write(fd, buf, n, IO_TIMEOUT) != n && syslog_flag) {
			syslog(LOG_NOTICE, "write to %s: %m", gethost6(faddr));
			return 1;
		}
		return 0;
	}

	if (userident_flag && getuserident(pw->pw_dir, token, sizeof token)) {
		syslog(LOG_NOTICE, "token \"%s\" == uid %u (%s)",
		    token, uid, pw->pw_name);
		if ((n = snprintf(buf, sizeof(buf),
		    "%d , %d : USERID : %s%s%s :%s\r\n", lport, fport,
		    opsys_name, charset_sep, charset_name, token))
		    >= sizeof(buf) || n < 0)
			n = strlen(buf);
		if (timed_write(fd, buf, n, IO_TIMEOUT) != n && syslog_flag) {
			syslog(LOG_NOTICE, "write to %s: %m", gethost6(faddr));
			return 1;
		}
		return 0;
	}

	if (token_flag) {
		gentoken(token, sizeof token);
		syslog(LOG_NOTICE, "token %s == uid %u (%s)", token, uid,
		    pw->pw_name);
		if ((n = snprintf(buf, sizeof(buf),
		    "%d , %d : USERID : %s%s%s :%s\r\n", lport, fport,
		    opsys_name, charset_sep, charset_name, token))
		    >= sizeof(buf) || n < 0)
			n = strlen(buf);
		if (timed_write(fd, buf, n, IO_TIMEOUT) != n && syslog_flag) {
			syslog(LOG_NOTICE, "write to %s: %m", gethost6(faddr));
			return 1;
		}
		return 0;
	}

	if (number_flag) {
		if ((n = snprintf(buf, sizeof(buf),
		    "%d , %d : USERID : %s%s%s :%u\r\n",
		    lport, fport, opsys_name, charset_sep, charset_name, uid))
		    >= sizeof(buf) || n < 0)
			n = strlen(buf);
		if (timed_write(fd, buf, n, IO_TIMEOUT) != n && syslog_flag) {
			syslog(LOG_NOTICE, "write to %s: %m", gethost6(faddr));
			return 1;
		}
		return 0;
	}

	if ((n = snprintf(buf, sizeof(buf), "%d , %d : USERID : %s%s%s :%s\r\n",
	    lport, fport, opsys_name, charset_sep, charset_name, pw->pw_name))
	    >= sizeof(buf) || n < 0)
		n = strlen(buf);
	if (timed_write(fd, buf, n, IO_TIMEOUT) != n && syslog_flag) {
		syslog(LOG_NOTICE, "write to %s: %m", gethost6(faddr));
		return 1;
	}
	return 0;
}
示例#21
0
文件: utils.c 项目: Audur/libpagekite
int http_get(const char* url, char* result_buffer, size_t maxlen)
{
  char *urlparse, *hostname, *port, *path;
  struct addrinfo hints, *result, *rp;
  char request[10240], *bp;
  int sockfd, rlen, bytes, total_bytes;

  /* http://hostname:port/foo */
  urlparse = strdup(url);
  hostname = urlparse+7;
  while (*hostname && *hostname == '/') hostname++;
  port = hostname;
  while (*port && *port != '/' && *port != ':') port++;
  if (*port == '/') {
    path = port;
    *path++ = '\0';
    port = (url[5] == 's') ? "443" : "80";
  }
  else {
    *port++ = '\0';
    path = port;
    while (*path && *path != '/') path++;
    *path++ = '\0';
  }

  rlen = snprintf(request, 10240,
                  "GET /%s HTTP/1.1\r\nHost: %s\r\n\r\n", path, hostname);
  if (10240 == rlen)
  {
    free(urlparse);
    return -1;
  }

  total_bytes = 0;
  memset(&hints, 0, sizeof(struct addrinfo));
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  if (0 == getaddrinfo(hostname, port, &hints, &result)) {
    for (rp = result; rp != NULL; rp = rp->ai_next) {
      if ((0 > (sockfd = socket(rp->ai_family, rp->ai_socktype,
                                rp->ai_protocol))) ||
          (0 > connect(sockfd, rp->ai_addr, rp->ai_addrlen)) ||
          (0 > write(sockfd, request, rlen)))
      {
        if (sockfd >= 0) close(sockfd);
      }
      else {
        total_bytes = 0;
        bp = result_buffer;
        do {
          bytes = timed_read(sockfd, bp, maxlen-(1+total_bytes), 1000);
          if (bytes > 0) {
            bp += bytes;
            total_bytes += bytes;
          }
        } while (bytes > 0);
        *bp = '\0';
        close(sockfd);
        break;
      }
    }
    freeaddrinfo(result);
  }
  free(urlparse);
  return total_bytes;
}
示例#22
0
void* pkb_tunnel_ping(void* void_fe) {
  struct pk_tunnel* fe = (struct pk_tunnel*) void_fe;
  struct timeval tv1, tv2, to;
  char buffer[1024], printip[1024];
  int sockfd, bytes, want;

  PK_TRACE_FUNCTION;

  fe->priority = 0;
  in_addr_to_str(fe->ai.ai_addr, printip, 1024);

  if (pk_state.fake_ping) {
    fe->priority = rand() % 500;
  }
  else {
    gettimeofday(&tv1, NULL);
    to.tv_sec = pk_state.socket_timeout_s;
    to.tv_usec = 0;
    if ((0 > (sockfd = PKS_socket(fe->ai.ai_family, fe->ai.ai_socktype,
                                  fe->ai.ai_protocol))) ||
        PKS_fail(PKS_setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *) &to, sizeof(to))) ||
        PKS_fail(PKS_setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *) &to, sizeof(to))) ||
        PKS_fail(PKS_connect(sockfd, fe->ai.ai_addr, fe->ai.ai_addrlen)) ||
        PKS_fail(PKS_write(sockfd, PK_FRONTEND_PING, strlen(PK_FRONTEND_PING))))
    {
      if (sockfd >= 0){
        PKS_close(sockfd);
      }
      if (fe->error_count < 999)
        fe->error_count += 1;
      pk_log(PK_LOG_MANAGER_DEBUG, "Ping %s failed! (connect)", printip);
      sleep(2); /* We don't want to return first! */
      return NULL;
    }

    /* Magic number: 116 bytes is the shortest response we expect. It is
     * still long enough to contain the X-PageKite-Overloaded marker, if
     * present at all. */
    bytes = timed_read(sockfd, buffer, 116, 1000);
    buffer[116] = '\0';

    want = strlen(PK_FRONTEND_PONG);
    if ((bytes < want) ||
        (0 != strncmp(buffer, PK_FRONTEND_PONG, want))) {
      if (fe->error_count < 999)
        fe->error_count += 1;
      pk_log(PK_LOG_MANAGER_DEBUG, "Ping %s failed! (read=%d)", printip, bytes);
      sleep(2); /* We don't want to return first! */
      return NULL;
    }
    PKS_close(sockfd);
    gettimeofday(&tv2, NULL);

    fe->priority = (tv2.tv_sec - tv1.tv_sec) * 1000
                 + (tv2.tv_usec - tv1.tv_usec) / 1000;

    if (strcasestr(buffer, PK_FRONTEND_OVERLOADED) != NULL) {
      fe->priority += 1;
      sleep(2); /* We don't want to return first! */
    }
  }

  if (fe->conn.status & (FE_STATUS_WANTED|FE_STATUS_IS_FAST))
  {
    /* Bias ping time to make old decisions a bit more sticky. We ignore
     * DNS though, to allow a bit of churn to spread the load around and
     * make sure new tunnels don't stay ignored forever. */
    fe->priority /= 10;
    fe->priority *= 9;
    pk_log(PK_LOG_MANAGER_DEBUG,
           "Ping %s: %dms (biased)", printip, fe->priority);
  }
  else {
    /* Add artificial +/-5% jitter to ping results */
    fe->priority *= ((rand() % 11) + 95);
    fe->priority /= 100;
    pk_log(PK_LOG_MANAGER_DEBUG, "Ping %s: %dms", printip, fe->priority);
  }

  PK_CHECK_MEMORY_CANARIES;
  return NULL;
}
示例#23
0
/*
  permitted -- return whether a given host is allowed to connect to the server.
*/
static int
permitted (unsigned long host_addr, int fd)
{
  int key;
  struct entry *entry;

  char auth_protocol[128];
  char buf[1024];
  int  auth_data_len;

  if (fd > 0)
    {
      /* we are checking permission on a real connection */

      /* Read auth protocol name */

      if (timed_read(fd, auth_protocol, AUTH_NAMESZ, AUTH_TIMEOUT, 1) <= 0)
	return FALSE;

      if (strcmp (auth_protocol, DEFAUTH_NAME) &&
	  strcmp (auth_protocol, MCOOKIE_NAME))
	{
	  printf ("authentication protocol (%s) from client is invalid...\n",
		  auth_protocol);
	  printf ("... Was the client an old version of gnuclient/gnudoit?\004\n");

	  return FALSE;
	}

      if (!strcmp(auth_protocol, MCOOKIE_NAME))
	{

	  /*
	   * doing magic cookie auth
	   */

	  if (timed_read (fd, buf, 10, AUTH_TIMEOUT, 1) <= 0)
	    return FALSE;

	  auth_data_len = atoi (buf);

	  if (auth_data_len <= 0 || auth_data_len > (int) sizeof (buf))
	      {
		return FALSE;
	      }

	  if (timed_read (fd, buf, auth_data_len, AUTH_TIMEOUT, 0) !=
	      auth_data_len)
	    return FALSE;

#ifdef AUTH_MAGIC_COOKIE
	  if (server_xauth && server_xauth->data)
	    {
	    /* Do a compare without comprising info about
	       the size of the cookie */
	    int auth_data_pos;
	    int auth_mismatches =
	      ( auth_data_len ^
		server_xauth->data_length );

	    for(auth_data_pos = 0; auth_data_pos < auth_data_len;
		++auth_data_pos)
	      auth_mismatches |=
		( buf[auth_data_pos] ^
		  server_xauth->data[auth_data_pos %
				     server_xauth->data_length]);

	    if (auth_mismatches == 0)
	      return TRUE;
	    
	    for(;rand() % 1000;);
	    }

#else
	  printf ("client tried Xauth, but server is not compiled with Xauth\n");
#endif

      /*
       * auth failed, but allow this to fall through to the GNU_SECURE
       * protocol....
       */

	  printf ("Xauth authentication failed, trying GNU_SECURE auth...\004\n");

	}

      /* Other auth protocols go here, and should execute only if the
       * auth_protocol name matches.
       */

    }


  /* Now, try the old GNU_SECURE stuff... */

  /* First find the hash key */
  key = HASH(host_addr) % TABLE_SIZE;

  /* Now check the chain for that hash key */
  for(entry=permitted_hosts[key]; entry != NULL; entry=entry->next)
    if (host_addr == entry->host_addr)
      return(TRUE);

  return(FALSE);

} /* permitted */