]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
c02345fe931c6af7342bf3dea90c1cb20a9e83e1
[user/henk/code/inspircd.git] / src / socket.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2008 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *            the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 /* $Core: libIRCDsocket */
15
16 #include "inspircd.h"
17 #include "socket.h"
18 #include "socketengine.h"
19
20 /* Private static member data must be initialized in this manner */
21 unsigned int ListenSocket::socketcount = 0;
22 sockaddr* ListenSocket::sock_us = NULL;
23 sockaddr* ListenSocket::client = NULL;
24 sockaddr* ListenSocket::raddr = NULL;
25
26 ListenSocket::ListenSocket(InspIRCd* Instance, int port, char* addr) : ServerInstance(Instance), desc("plaintext"), bind_addr(addr), bind_port(port)
27 {
28         this->SetFd(irc::sockets::OpenTCPSocket(addr));
29         if (this->GetFd() > -1)
30         {
31                 if (!Instance->BindSocket(this->fd,port,addr))
32                         this->fd = -1;
33 #ifdef IPV6
34                 if ((!*addr) || (strchr(addr,':')))
35                         this->family = AF_INET6;
36                 else
37 #endif
38                 this->family = AF_INET;
39                 Instance->SE->AddFd(this);
40         }
41         /* Saves needless allocations */
42         if (socketcount == 0)
43         {
44                 /* All instances of ListenSocket share these, so reference count it */
45                 ServerInstance->Logs->Log("SOCKET", DEBUG,"Allocate sockaddr structures");
46                 sock_us = new sockaddr[2];
47                 client = new sockaddr[2];
48                 raddr = new sockaddr[2];
49         }
50         socketcount++;
51 }
52
53 ListenSocket::~ListenSocket()
54 {
55         if (this->GetFd() > -1)
56         {
57                 ServerInstance->SE->DelFd(this);
58                 ServerInstance->Logs->Log("SOCKET", DEBUG,"Shut down listener on fd %d", this->fd);
59                 if (ServerInstance->SE->Shutdown(this, 2) || ServerInstance->SE->Close(this))
60                         ServerInstance->Logs->Log("SOCKET", DEBUG,"Failed to cancel listener: %s", strerror(errno));
61                 this->fd = -1;
62         }
63         socketcount--;
64         if (socketcount == 0)
65         {
66                 delete[] sock_us;
67                 delete[] client;
68                 delete[] raddr;
69         }
70 }
71
72 void ListenSocket::HandleEvent(EventType e, int err)
73 {
74         switch (e)
75         {
76                 case EVENT_ERROR:
77                         ServerInstance->Logs->Log("SOCKET",DEFAULT,"ListenSocket::HandleEvent() received a socket engine error event! well shit! '%s'", strerror(err));
78                 break;
79                 case EVENT_WRITE:
80                         ServerInstance->Logs->Log("SOCKET",DEBUG,"*** BUG *** ListenSocket::HandleEvent() got a WRITE event!!!");
81                 break;
82                 case EVENT_READ:
83                 {
84                         ServerInstance->Logs->Log("SOCKET",DEBUG,"HandleEvent for Listensoket");
85                         socklen_t uslen, length;                // length of our port number
86                         int incomingSockfd, in_port;
87
88 #ifdef IPV6
89                         if (this->family == AF_INET6)
90                         {
91                                 uslen = sizeof(sockaddr_in6);
92                                 length = sizeof(sockaddr_in6);
93                         }
94                         else
95 #endif
96                         {
97                                 uslen = sizeof(sockaddr_in);
98                                 length = sizeof(sockaddr_in);
99                         }
100
101                         incomingSockfd = ServerInstance->SE->Accept(this, (sockaddr*)client, &length);
102
103                         if ((incomingSockfd > -1) && (!ServerInstance->SE->GetSockName(this, sock_us, &uslen)))
104                         {
105                                 char buf[MAXBUF];
106                                 char target[MAXBUF];    
107
108                                 *target = *buf = '\0';
109
110 #ifdef IPV6
111                                 if (this->family == AF_INET6)
112                                 {
113                                         in_port = ntohs(((sockaddr_in6*)sock_us)->sin6_port);
114                                         inet_ntop(AF_INET6, &((const sockaddr_in6*)client)->sin6_addr, buf, sizeof(buf));
115                                         socklen_t raddrsz = sizeof(sockaddr_in6);
116                                         if (getsockname(incomingSockfd, (sockaddr*) raddr, &raddrsz) == 0)
117                                                 inet_ntop(AF_INET6, &((const sockaddr_in6*)raddr)->sin6_addr, target, sizeof(target));
118                                         else
119                                                 ServerInstance->Logs->Log("SOCKET", DEBUG, "Can't get peername: %s", strerror(errno));
120                                 }
121                                 else
122 #endif
123                                 {
124                                         inet_ntop(AF_INET, &((const sockaddr_in*)client)->sin_addr, buf, sizeof(buf));
125                                         in_port = ntohs(((sockaddr_in*)sock_us)->sin_port);
126                                         socklen_t raddrsz = sizeof(sockaddr_in);
127                                         if (getsockname(incomingSockfd, (sockaddr*) raddr, &raddrsz) == 0)
128                                                 inet_ntop(AF_INET, &((const sockaddr_in*)raddr)->sin_addr, target, sizeof(target));
129                                         else
130                                                 ServerInstance->Logs->Log("SOCKET", DEBUG, "Can't get peername: %s", strerror(errno));
131                                 }
132                                 ServerInstance->SE->NonBlocking(incomingSockfd);
133                                 ServerInstance->stats->statsAccept++;
134                                 ServerInstance->Users->AddUser(ServerInstance, incomingSockfd, in_port, false, this->family, client, target);   
135                         }
136                         else
137                         {
138                                 ServerInstance->SE->Shutdown(incomingSockfd, 2);
139                                 ServerInstance->SE->Close(incomingSockfd);
140                                 ServerInstance->stats->statsRefused++;
141                         }
142                 }
143                 break;
144         }
145 }
146
147 /** This will bind a socket to a port. It works for UDP/TCP.
148  * It can only bind to IP addresses, if you wish to bind to hostnames
149  * you should first resolve them using class 'Resolver'.
150  */ 
151 bool InspIRCd::BindSocket(int sockfd, int port, const char* addr, bool dolisten)
152 {
153         /* We allocate 2 of these, because sockaddr_in6 is larger than sockaddr (ugh, hax) */
154         sockaddr* servaddr = new sockaddr[2];
155         memset(servaddr,0,sizeof(sockaddr)*2);
156
157         int ret, size;
158
159         if (*addr == '*')
160                 addr = "";
161
162 #ifdef IPV6
163         if (*addr)
164         {
165                 /* There is an address here. Is it ipv6? */
166                 if (strchr(addr,':'))
167                 {
168                         /* Yes it is */
169                         in6_addr addy;
170                         if (inet_pton(AF_INET6, addr, &addy) < 1)
171                         {
172                                 delete[] servaddr;
173                                 return false;
174                         }
175
176                         ((sockaddr_in6*)servaddr)->sin6_family = AF_INET6;
177                         memcpy(&(((sockaddr_in6*)servaddr)->sin6_addr), &addy, sizeof(in6_addr));
178                         ((sockaddr_in6*)servaddr)->sin6_port = htons(port);
179                         size = sizeof(sockaddr_in6);
180                 }
181                 else
182                 {
183                         /* No, its not */
184                         in_addr addy;
185                         if (inet_pton(AF_INET, addr, &addy) < 1)
186                         {
187                                 delete[] servaddr;
188                                 return false;
189                         }
190
191                         ((sockaddr_in*)servaddr)->sin_family = AF_INET;
192                         ((sockaddr_in*)servaddr)->sin_addr = addy;
193                         ((sockaddr_in*)servaddr)->sin_port = htons(port);
194                         size = sizeof(sockaddr_in);
195                 }
196         }
197         else
198         {
199                 if (port == -1)
200                 {
201                         /* Port -1: Means UDP IPV4 port binding - Special case
202                          * used by DNS engine.
203                          */
204                         ((sockaddr_in*)servaddr)->sin_family = AF_INET;
205                         ((sockaddr_in*)servaddr)->sin_addr.s_addr = htonl(INADDR_ANY);
206                         ((sockaddr_in*)servaddr)->sin_port = 0;
207                         size = sizeof(sockaddr_in);
208                 }
209                 else
210                 {
211                         /* Theres no address here, default to ipv6 bind to all */
212                         ((sockaddr_in6*)servaddr)->sin6_family = AF_INET6;
213                         memset(&(((sockaddr_in6*)servaddr)->sin6_addr), 0, sizeof(in6_addr));
214                         ((sockaddr_in6*)servaddr)->sin6_port = htons(port);
215                         size = sizeof(sockaddr_in6);
216                 }
217         }
218 #else
219         /* If we aren't built with ipv6, the choice becomes simple */
220         ((sockaddr_in*)servaddr)->sin_family = AF_INET;
221         if (*addr)
222         {
223                 /* There is an address here. */
224                 in_addr addy;
225                 if (inet_pton(AF_INET, addr, &addy) < 1)
226                 {
227                         delete[] servaddr;
228                         return false;
229                 }
230                 ((sockaddr_in*)servaddr)->sin_addr = addy;
231         }
232         else
233         {
234                 /* Bind ipv4 to all */
235                 ((sockaddr_in*)servaddr)->sin_addr.s_addr = htonl(INADDR_ANY);
236         }
237         /* Bind ipv4 port number */
238         ((sockaddr_in*)servaddr)->sin_port = htons(port);
239         size = sizeof(sockaddr_in);
240 #endif
241         ret = SE->Bind(sockfd, servaddr, size);
242         delete[] servaddr;
243
244         if (ret < 0)
245         {
246                 return false;
247         }
248         else
249         {
250                 if (dolisten)
251                 {
252                         if (SE->Listen(sockfd, Config->MaxConn) == -1)
253                         {
254                                 this->Logs->Log("SOCKET",DEFAULT,"ERROR in listen(): %s",strerror(errno));
255                                 return false;
256                         }
257                         else
258                         {
259                                 this->Logs->Log("SOCKET",DEBUG,"New socket binding for %d with listen: %s:%d", sockfd, addr, port);
260                                 SE->NonBlocking(sockfd);
261                                 return true;
262                         }
263                 }
264                 else
265                 {
266                         this->Logs->Log("SOCKET",DEBUG,"New socket binding for %d without listen: %s:%d", sockfd, addr, port);
267                         return true;
268                 }
269         }
270 }
271
272 // Open a TCP Socket
273 int irc::sockets::OpenTCPSocket(char* addr, int socktype)
274 {
275         int sockfd;
276         int on = 1;
277         addr = addr;
278         struct linger linger = { 0, 0 };
279 #ifdef IPV6
280         if (strchr(addr,':') || (!*addr))
281                 sockfd = socket (PF_INET6, socktype, 0);
282         else
283                 sockfd = socket (PF_INET, socktype, 0);
284         if (sockfd < 0)
285 #else
286         if ((sockfd = socket (PF_INET, socktype, 0)) < 0)
287 #endif
288         {
289                 return ERROR;
290         }
291         else
292         {
293                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
294                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
295                 linger.l_onoff = 1;
296                 linger.l_linger = 1;
297                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (char*)&linger,sizeof(linger));
298                 return (sockfd);
299         }
300 }
301
302 int InspIRCd::BindPorts(bool, int &ports_found, FailedPortList &failed_ports)
303 {
304         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
305         int bound = 0;
306         bool started_with_nothing = (Config->ports.size() == 0);
307         std::vector<std::pair<std::string, int> > old_ports;
308
309         /* XXX: Make a copy of the old ip/port pairs here */
310         for (std::vector<ListenSocket*>::iterator o = Config->ports.begin(); o != Config->ports.end(); ++o)
311                 old_ports.push_back(make_pair((*o)->GetIP(), (*o)->GetPort()));
312
313         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
314         {
315                 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
316                 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
317                 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
318                 
319                 if (strncmp(Addr, "::ffff:", 7) == 0)
320                         this->Logs->Log("SOCKET",DEFAULT, "Using 4in6 (::ffff:) isn't recommended. You should bind IPv4 addresses directly instead.");
321                 
322                 if ((!*Type) || (!strcmp(Type,"clients")))
323                 {
324                         irc::portparser portrange(configToken, false);
325                         int portno = -1;
326                         while (0 != (portno = portrange.GetToken()))
327                         {
328                                 if (*Addr == '*')
329                                         *Addr = 0;
330
331                                 bool skip = false;
332                                 for (std::vector<ListenSocket*>::iterator n = Config->ports.begin(); n != Config->ports.end(); ++n)
333                                 {
334                                         if (((*n)->GetIP() == Addr) && ((*n)->GetPort() == portno))
335                                         {
336                                                 skip = true;
337                                                 /* XXX: Here, erase from our copy of the list */
338                                                 for (std::vector<std::pair<std::string, int> >::iterator k = old_ports.begin(); k != old_ports.end(); ++k)
339                                                 {
340                                                         if ((k->first == Addr) && (k->second == portno))
341                                                         {
342                                                                 old_ports.erase(k);
343                                                                 break;
344                                                         }
345                                                 }
346                                         }
347                                 }
348                                 if (!skip)
349                                 {
350                                         ListenSocket* ll = new ListenSocket(this, portno, Addr);
351                                         if (ll->GetFd() > -1)
352                                         {
353                                                 bound++;
354                                                 Config->ports.push_back(ll);
355                                         }
356                                         else
357                                         {
358                                                 failed_ports.push_back(std::make_pair((*Addr ? Addr : "*") + std::string(":") + ConvToStr(portno), strerror(errno)));
359                                         }
360                                         ports_found++;
361                                 }
362                         }
363                 }
364         }
365
366         /* XXX: Here, anything left in our copy list, close as removed */
367         if (!started_with_nothing)
368         {
369                 for (size_t k = 0; k < old_ports.size(); ++k)
370                 {
371                         for (std::vector<ListenSocket*>::iterator n = Config->ports.begin(); n != Config->ports.end(); ++n)
372                         {
373                                 if (((*n)->GetIP() == old_ports[k].first) && ((*n)->GetPort() == old_ports[k].second))
374                                 {
375                                         this->Logs->Log("SOCKET",DEFAULT,"Port binding %s:%d was removed from the config file, closing.", old_ports[k].first.c_str(), old_ports[k].second);
376                                         delete *n;
377                                         Config->ports.erase(n);
378                                         break;
379                                 }
380                         }
381                 }
382         }
383
384         return bound;
385 }
386
387 const char* irc::sockets::insp_ntoa(insp_inaddr n)
388 {
389         static char buf[1024];
390         inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
391         return buf;
392 }
393
394 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
395 {
396         return inet_pton(AF_FAMILY, a, n);
397 }
398
399