stream: add a stream class abstracting BSD sockets
[strongswan.git] / src / libstrongswan / networking / streams / stream.h
1 /*
2 * Copyright (C) 2013 Martin Willi
3 * Copyright (C) 2013 revosec AG
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 /**
17 * @defgroup stream stream
18 * @{ @ingroup streams
19 */
20
21 #ifndef STREAM_H_
22 #define STREAM_H_
23
24 typedef struct stream_t stream_t;
25
26 #include <library.h>
27
28 /**
29 * Constructor function prototype for stream_t.
30 *
31 * @param uri URI to create a stream for
32 * @return stream instance, NULL on error
33 */
34 typedef stream_t*(*stream_constructor_t)(char *uri);
35
36 /**
37 * Abstraction of a Berkley socket using stream semantics.
38 */
39 struct stream_t {
40
41 /**
42 * Read data from the stream.
43 *
44 * If "block" is FALSE and no data is available, the function returns -1
45 * and sets errno to EWOULDBLOCK.
46 *
47 * @param buf data buffer to read into
48 * @param len number of bytes to read
49 * @param block TRUE to use a blocking read
50 * @return number of bytes read, -1 on error
51 */
52 ssize_t (*read)(stream_t *this, void *buf, size_t len, bool block);
53
54 /**
55 * Write data to the stream.
56 *
57 * If "block" is FALSE and the write would block, the function returns -1
58 * and sets errno to EWOULDBLOCK.
59 *
60 * @param buf data buffer to write
61 * @param len number of bytes to write
62 * @param block TRUE to use a blocking write
63 * @return number of bytes written, -1 on error
64 */
65 ssize_t (*write)(stream_t *this, void *buf, size_t len, bool block);
66
67 /**
68 * Destroy a stream_t.
69 */
70 void (*destroy)(stream_t *this);
71 };
72
73 /**
74 * Create a stream from a file descriptor.
75 *
76 * The file descriptor MUST be a socket for non-blocking operation.
77 *
78 * @param fd file descriptor to wrap into a stream_t
79 * @return stream instance
80 */
81 stream_t *stream_create_from_fd(int fd);
82
83 #endif /** STREAM_H_ @}*/