util.c 1.58 KB
Newer Older
Jack Moffitt's avatar
Jack Moffitt committed
1 2 3
#include <sys/types.h>

#ifndef _WIN32
4 5
#include <sys/time.h>
#include <sys/socket.h>
Jack Moffitt's avatar
Jack Moffitt committed
6
#include <unistd.h>
7 8 9
#ifdef HAVE_POLL
#include <sys/poll.h>
#endif
10
#else
11
#include <winsock2.h>
12
#include <windows.h>
Jack Moffitt's avatar
Jack Moffitt committed
13 14 15 16 17 18 19
#endif

#include "sock.h"

#include "config.h"
#include "util.h"

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
/* Abstract out an interface to use either poll or select depending on which
 * is available (poll is preferred) to watch a single fd.
 *
 * timeout is in milliseconds.
 *
 * returns > 0 if activity on the fd occurs before the timeout.
 *           0 if no activity occurs
 *         < 0 for error.
 */
int util_timed_wait_for_fd(int fd, int timeout)
{
#ifdef HAVE_POLL
    struct pollfd ufds;

    ufds.fd = fd;
    ufds.events = POLLIN;
    ufds.revents = 0;

    return poll(&ufds, 1, timeout);
#else
    fd_set rfds;
    struct timeval tv;

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

    tv.tv_sec = timeout/1000;
    tv.tv_usec = (timeout - tv.tv_sec)*1000;

    return select(fd+1, &rfds, NULL, NULL, &tv);
#endif
}

Jack Moffitt's avatar
Jack Moffitt committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
int util_read_header(int sock, char *buff, unsigned long len)
{
	int read_bytes, ret;
	unsigned long pos;
	char c;
	ice_config_t *config;

	config = config_get_config();

	read_bytes = 1;
	pos = 0;
	ret = 0;

	while ((read_bytes == 1) && (pos < (len - 1))) {
		read_bytes = 0;

69
        if (util_timed_wait_for_fd(sock, config->header_timeout*1000) > 0) {
Jack Moffitt's avatar
Jack Moffitt committed
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90

			if ((read_bytes = recv(sock, &c, 1, 0))) {
				if (c != '\r') buff[pos++] = c;
				if ((pos > 1) && (buff[pos - 1] == '\n' && buff[pos - 2] == '\n')) {
					ret = 1;
					break;
				}
			}
		} else {
			break;
		}
	}

	if (ret) buff[pos] = '\0';
	
	return ret;
}