]> granicus.if.org Git - icinga2/blob - lib/base/unixsocket.cpp
Merge pull request #7185 from Icinga/bugfix/gelfwriter-wrong-log-facility
[icinga2] / lib / base / unixsocket.cpp
1 /* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
2
3 #include "base/unixsocket.hpp"
4 #include "base/exception.hpp"
5
6 #ifndef _WIN32
7 using namespace icinga;
8
9 UnixSocket::UnixSocket()
10 {
11         int fd = socket(AF_UNIX, SOCK_STREAM, 0);
12
13         if (fd < 0) {
14                 BOOST_THROW_EXCEPTION(posix_error()
15                         << boost::errinfo_api_function("socket")
16                         << boost::errinfo_errno(errno));
17         }
18
19         SetFD(fd);
20 }
21
22 void UnixSocket::Bind(const String& path)
23 {
24         unlink(path.CStr());
25
26         sockaddr_un s_un;
27         memset(&s_un, 0, sizeof(s_un));
28         s_un.sun_family = AF_UNIX;
29         strncpy(s_un.sun_path, path.CStr(), sizeof(s_un.sun_path));
30         s_un.sun_path[sizeof(s_un.sun_path) - 1] = '\0';
31
32         if (bind(GetFD(), (sockaddr *)&s_un, SUN_LEN(&s_un)) < 0) {
33                 BOOST_THROW_EXCEPTION(posix_error()
34                         << boost::errinfo_api_function("bind")
35                         << boost::errinfo_errno(errno));
36         }
37 }
38
39 void UnixSocket::Connect(const String& path)
40 {
41         sockaddr_un s_un;
42         memset(&s_un, 0, sizeof(s_un));
43         s_un.sun_family = AF_UNIX;
44         strncpy(s_un.sun_path, path.CStr(), sizeof(s_un.sun_path));
45         s_un.sun_path[sizeof(s_un.sun_path) - 1] = '\0';
46
47         if (connect(GetFD(), (sockaddr *)&s_un, SUN_LEN(&s_un)) < 0 && errno != EINPROGRESS) {
48                 BOOST_THROW_EXCEPTION(posix_error()
49                         << boost::errinfo_api_function("connect")
50                         << boost::errinfo_errno(errno));
51         }
52 }
53 #endif /* _WIN32 */