update README
[rofl0r-rocksock.git] / rocksock_peek.c
blob43d54de1929716d5bedeee2bd321f619462fb703
1 /*
2 * author: rofl0r (C) 2011-2013
3 * License: LGPL 2.1+ with static linking exception
4 */
6 #undef _POSIX_C_SOURCE
7 #define _POSIX_C_SOURCE 200809L
8 #undef _GNU_SOURCE
9 #define _GNU_SOURCE
11 #include <stdio.h>
12 #include <sys/select.h>
13 #include <netinet/in.h>
14 #include <errno.h>
16 #include "rocksock.h"
17 #include "rocksock_internal.h"
18 #ifdef USE_SSL
19 #include "rocksock_ssl_internal.h"
20 #endif
22 #ifndef ROCKSOCK_FILENAME
23 #define ROCKSOCK_FILENAME __FILE__
24 #endif
27 return value: error code or 0 for no error
28 result will contain 0 if no data is available, 1 if data is available.
29 if data is available, and a subsequent recv call returns 0 bytes read, the
30 connection was terminated. */
31 int rocksock_peek(rocksock* sock, int *result) {
32 ssize_t readv;
33 if(!result)
34 return rocksock_seterror(sock, RS_ET_OWN, RS_E_NULL, ROCKSOCK_FILENAME, __LINE__);
35 #ifdef USE_SSL
36 if(sock->ssl && rocksock_ssl_pending(sock)) {
37 *result = 1;
38 goto no_err;
40 #endif
41 fd_set readfds;
43 struct timeval tv;
44 tv.tv_sec = 0;
45 tv.tv_usec = 1;
46 FD_ZERO(&readfds);
47 FD_SET(sock->socket, &readfds);
49 readv = select(sock->socket + 1, &readfds, 0, 0, &tv);
50 if(readv < 0) return rocksock_seterror(sock, RS_ET_SYS, errno, ROCKSOCK_FILENAME, __LINE__);
51 *result = FD_ISSET(sock->socket, &readfds);
52 #ifdef USE_SSL
53 if(sock->ssl && *result) {
54 return rocksock_ssl_peek(sock, result);
56 no_err:
57 #endif
58 return rocksock_seterror(sock, RS_ET_NO_ERROR, 0, NULL, 0);