]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/listensocket.cpp
Merge insp20
[user/henk/code/inspircd.git] / src / listensocket.cpp
1 /*
2  * InspIRCd -- Internet Relay Chat Daemon
3  *
4  *   Copyright (C) 2009-2010 Daniel De Graaf <danieldg@inspircd.org>
5  *   Copyright (C) 2008 Robin Burchell <robin+git@viroteck.net>
6  *
7  * This file is part of InspIRCd.  InspIRCd is free software: you can
8  * redistribute it and/or modify it under the terms of the GNU General Public
9  * License as published by the Free Software Foundation, version 2.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13  * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20
21 #include "inspircd.h"
22
23 #ifndef _WIN32
24 #include <netinet/tcp.h>
25 #endif
26
27 ListenSocket::ListenSocket(ConfigTag* tag, const irc::sockets::sockaddrs& bind_to)
28         : bind_tag(tag)
29         , iohookprov(NULL, std::string())
30 {
31         irc::sockets::satoap(bind_to, bind_addr, bind_port);
32         bind_desc = bind_to.str();
33
34         fd = socket(bind_to.sa.sa_family, SOCK_STREAM, 0);
35
36         if (this->fd == -1)
37                 return;
38
39 #ifdef IPV6_V6ONLY
40         /* This OS supports IPv6 sockets that can also listen for IPv4
41          * connections. If our address is "*" or empty, enable both v4 and v6 to
42          * allow for simpler configuration on dual-stack hosts. Otherwise, if it
43          * is "::" or an IPv6 address, disable support so that an IPv4 bind will
44          * work on the port (by us or another application).
45          */
46         if (bind_to.sa.sa_family == AF_INET6)
47         {
48                 std::string addr = tag->getString("address");
49                 /* This must be >= sizeof(DWORD) on Windows */
50                 const int enable = (addr.empty() || addr == "*") ? 0 : 1;
51                 /* This must be before bind() */
52                 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&enable), sizeof(enable));
53                 // errors ignored intentionally
54         }
55 #endif
56
57         SocketEngine::SetReuse(fd);
58         int rv = SocketEngine::Bind(this->fd, bind_to);
59         if (rv >= 0)
60                 rv = SocketEngine::Listen(this->fd, ServerInstance->Config->MaxConn);
61
62         int timeout = tag->getInt("defer", 0);
63         if (timeout && !rv)
64         {
65 #if defined TCP_DEFER_ACCEPT
66                 setsockopt(fd, IPPROTO_TCP, TCP_DEFER_ACCEPT, &timeout, sizeof(timeout));
67 #elif defined SO_ACCEPTFILTER
68                 struct accept_filter_arg afa;
69                 memset(&afa, 0, sizeof(afa));
70                 strcpy(afa.af_name, "dataready");
71                 setsockopt(fd, SOL_SOCKET, SO_ACCEPTFILTER, &afa, sizeof(afa));
72 #endif
73         }
74
75         if (rv < 0)
76         {
77                 int errstore = errno;
78                 SocketEngine::Shutdown(this, 2);
79                 SocketEngine::Close(this->GetFd());
80                 this->fd = -1;
81                 errno = errstore;
82         }
83         else
84         {
85                 SocketEngine::NonBlocking(this->fd);
86                 SocketEngine::AddFd(this, FD_WANT_POLL_READ | FD_WANT_NO_WRITE);
87
88                 this->ResetIOHookProvider();
89         }
90 }
91
92 ListenSocket::~ListenSocket()
93 {
94         if (this->GetFd() > -1)
95         {
96                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Shut down listener on fd %d", this->fd);
97                 SocketEngine::Shutdown(this, 2);
98                 if (SocketEngine::Close(this) != 0)
99                         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Failed to cancel listener: %s", strerror(errno));
100         }
101 }
102
103 /* Just seperated into another func for tidiness really.. */
104 void ListenSocket::AcceptInternal()
105 {
106         irc::sockets::sockaddrs client;
107         irc::sockets::sockaddrs server;
108
109         socklen_t length = sizeof(client);
110         int incomingSockfd = SocketEngine::Accept(this, &client.sa, &length);
111
112         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "HandleEvent for Listensocket %s nfd=%d", bind_desc.c_str(), incomingSockfd);
113         if (incomingSockfd < 0)
114         {
115                 ServerInstance->stats.Refused++;
116                 return;
117         }
118
119         socklen_t sz = sizeof(server);
120         if (getsockname(incomingSockfd, &server.sa, &sz))
121         {
122                 ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "Can't get peername: %s", strerror(errno));
123                 irc::sockets::aptosa(bind_addr, bind_port, server);
124         }
125
126         if (client.sa.sa_family == AF_INET6)
127         {
128                 /*
129                  * This case is the be all and end all patch to catch and nuke 4in6
130                  * instead of special-casing shit all over the place and wreaking merry
131                  * havoc with crap, instead, we just recreate sockaddr and strip ::ffff: prefix
132                  * if it's a 4in6 IP.
133                  *
134                  * This is, of course, much improved over the older way of handling this
135                  * (pretend it doesn't exist + hack around it -- yes, both were done!)
136                  *
137                  * Big, big thanks to danieldg for his work on this.
138                  * -- w00t
139                  */
140                 static const unsigned char prefix4in6[12] = { 0,0,0,0, 0,0,0,0, 0,0,0xFF,0xFF };
141                 if (!memcmp(prefix4in6, &client.in6.sin6_addr, 12))
142                 {
143                         // recreate as a sockaddr_in using the IPv4 IP
144                         uint16_t sport = client.in6.sin6_port;
145                         client.in4.sin_family = AF_INET;
146                         client.in4.sin_port = sport;
147                         memcpy(&client.in4.sin_addr.s_addr, client.in6.sin6_addr.s6_addr + 12, sizeof(uint32_t));
148
149                         sport = server.in6.sin6_port;
150                         server.in4.sin_family = AF_INET;
151                         server.in4.sin_port = sport;
152                         memcpy(&server.in4.sin_addr.s_addr, server.in6.sin6_addr.s6_addr + 12, sizeof(uint32_t));
153                 }
154         }
155
156         SocketEngine::NonBlocking(incomingSockfd);
157
158         ModResult res;
159         FIRST_MOD_RESULT(OnAcceptConnection, res, (incomingSockfd, this, &client, &server));
160         if (res == MOD_RES_PASSTHRU)
161         {
162                 std::string type = bind_tag->getString("type", "clients");
163                 if (type == "clients")
164                 {
165                         ServerInstance->Users->AddUser(incomingSockfd, this, &client, &server);
166                         res = MOD_RES_ALLOW;
167                 }
168         }
169         if (res == MOD_RES_ALLOW)
170         {
171                 ServerInstance->stats.Accept++;
172         }
173         else
174         {
175                 ServerInstance->stats.Refused++;
176                 ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "Refusing connection on %s - %s",
177                         bind_desc.c_str(), res == MOD_RES_DENY ? "Connection refused by module" : "Module for this port not found");
178                 SocketEngine::Close(incomingSockfd);
179         }
180 }
181
182 void ListenSocket::HandleEvent(EventType e, int err)
183 {
184         switch (e)
185         {
186                 case EVENT_ERROR:
187                         ServerInstance->Logs->Log("SOCKET", LOG_DEFAULT, "ListenSocket::HandleEvent() received a socket engine error event! well shit! '%s'", strerror(err));
188                         break;
189                 case EVENT_WRITE:
190                         ServerInstance->Logs->Log("SOCKET", LOG_DEBUG, "*** BUG *** ListenSocket::HandleEvent() got a WRITE event!!!");
191                         break;
192                 case EVENT_READ:
193                         this->AcceptInternal();
194                         break;
195         }
196 }
197
198 bool ListenSocket::ResetIOHookProvider()
199 {
200         std::string provname = bind_tag->getString("ssl");
201         if (!provname.empty())
202                 provname.insert(0, "ssl/");
203
204         // Set the new provider name, dynref handles the rest
205         iohookprov.SetProvider(provname);
206
207         // Return true if no provider was set, or one was set and it was also found
208         return (provname.empty() || iohookprov);
209 }