]> git.tdb.fi Git - libs/net.git/blob - source/net/unix/socket.cpp
970b9aedd3be443dff55e6500a296719041ea678
[libs/net.git] / source / net / unix / socket.cpp
1 #include <cerrno>
2 #include <unistd.h>
3 #include <fcntl.h>
4 #include "platform_api.h"
5 #include <msp/core/systemerror.h>
6 #include <msp/io/handle_private.h>
7 #include <msp/time/rawtime_private.h>
8 #include "sockaddr_private.h"
9 #include "socket.h"
10 #include "socket_private.h"
11
12 namespace Msp {
13 namespace Net {
14
15 void Socket::platform_init()
16 {
17         *priv->event = priv->handle;
18         set_inherit(false);
19 }
20
21 void Socket::platform_cleanup()
22 {
23         close(priv->handle);
24 }
25
26 void Socket::set_timeout(const Time::TimeDelta &timeout)
27 {
28         timeval tv = Time::rawtime_to_timeval(timeout.raw());
29         priv->set_option(SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(timeval));
30         priv->set_option(SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(timeval));
31 }
32
33 void Socket::set_platform_events(unsigned)
34 {
35 }
36
37
38 void Socket::Private::set_block(bool b)
39 {
40         int flags = fcntl(handle, F_GETFL);
41         fcntl(handle, F_SETFL, (flags&~O_NONBLOCK)|(b?0:O_NONBLOCK));
42 }
43
44 void Socket::Private::set_inherit(bool i)
45 {
46         int flags = fcntl(handle, F_GETFD);
47         fcntl(handle, F_SETFD, (flags&~O_CLOEXEC)|(i?0:O_CLOEXEC));
48 }
49
50 int Socket::Private::set_option(int level, int optname, const void *optval, socklen_t optlen)
51 {
52         return setsockopt(handle, level, optname, optval, optlen);
53 }
54
55 int Socket::Private::get_option(int level, int optname, void *optval, socklen_t *optlen)
56 {
57         return getsockopt(handle, level, optname, optval, optlen);
58 }
59
60
61 unsigned check_sys_error(int ret, const char *func)
62 {
63         if(ret<0)
64         {
65                 if(errno==EAGAIN)
66                         return 0;
67                 else
68                         throw system_error(func);
69         }
70
71         return ret;
72 }
73
74 bool check_sys_connect_error(int ret)
75 {
76         if(ret<0)
77         {
78                 if(errno==EINPROGRESS)
79                         return false;
80                 else
81                         throw system_error("connect");
82         }
83
84         return true;
85 }
86
87 } // namespace Net
88 } // namespace Msp