]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/socket.cpp
Microsoft, in their "infinite wisdom" decide to have no sensible naming convention...
[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 (getpeername(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 (getpeername(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
133                                 ServerInstance->SE->NonBlocking(incomingSockfd);
134                                 ServerInstance->stats->statsAccept++;
135                                 ServerInstance->Users->AddUser(ServerInstance, incomingSockfd, in_port, false, this->family, client, target);   
136                         }
137                         else
138                         {
139                                 ServerInstance->SE->Shutdown(incomingSockfd, 2);
140                                 ServerInstance->SE->Close(incomingSockfd);
141                                 ServerInstance->stats->statsRefused++;
142                         }
143                 }
144                 break;
145         }
146 }
147
148 /** This will bind a socket to a port. It works for UDP/TCP.
149  * It can only bind to IP addresses, if you wish to bind to hostnames
150  * you should first resolve them using class 'Resolver'.
151  */ 
152 bool InspIRCd::BindSocket(int sockfd, int port, const char* addr, bool dolisten)
153 {
154         /* We allocate 2 of these, because sockaddr_in6 is larger than sockaddr (ugh, hax) */
155         sockaddr* servaddr = new sockaddr[2];
156         memset(servaddr,0,sizeof(sockaddr)*2);
157
158         int ret, size;
159
160         if (*addr == '*')
161                 addr = "";
162
163 #ifdef IPV6
164         if (*addr)
165         {
166                 /* There is an address here. Is it ipv6? */
167                 if (strchr(addr,':'))
168                 {
169                         /* Yes it is */
170                         in6_addr addy;
171                         if (inet_pton(AF_INET6, addr, &addy) < 1)
172                         {
173                                 delete[] servaddr;
174                                 return false;
175                         }
176
177                         ((sockaddr_in6*)servaddr)->sin6_family = AF_INET6;
178                         memcpy(&(((sockaddr_in6*)servaddr)->sin6_addr), &addy, sizeof(in6_addr));
179                         ((sockaddr_in6*)servaddr)->sin6_port = htons(port);
180                         size = sizeof(sockaddr_in6);
181                 }
182                 else
183                 {
184                         /* No, its not */
185                         in_addr addy;
186                         if (inet_pton(AF_INET, addr, &addy) < 1)
187                         {
188                                 delete[] servaddr;
189                                 return false;
190                         }
191
192                         ((sockaddr_in*)servaddr)->sin_family = AF_INET;
193                         ((sockaddr_in*)servaddr)->sin_addr = addy;
194                         ((sockaddr_in*)servaddr)->sin_port = htons(port);
195                         size = sizeof(sockaddr_in);
196                 }
197         }
198         else
199         {
200                 if (port == -1)
201                 {
202                         /* Port -1: Means UDP IPV4 port binding - Special case
203                          * used by DNS engine.
204                          */
205                         ((sockaddr_in*)servaddr)->sin_family = AF_INET;
206                         ((sockaddr_in*)servaddr)->sin_addr.s_addr = htonl(INADDR_ANY);
207                         ((sockaddr_in*)servaddr)->sin_port = 0;
208                         size = sizeof(sockaddr_in);
209                 }
210                 else
211                 {
212                         /* Theres no address here, default to ipv6 bind to all */
213                         ((sockaddr_in6*)servaddr)->sin6_family = AF_INET6;
214                         memset(&(((sockaddr_in6*)servaddr)->sin6_addr), 0, sizeof(in6_addr));
215                         ((sockaddr_in6*)servaddr)->sin6_port = htons(port);
216                         size = sizeof(sockaddr_in6);
217                 }
218         }
219 #else
220         /* If we aren't built with ipv6, the choice becomes simple */
221         ((sockaddr_in*)servaddr)->sin_family = AF_INET;
222         if (*addr)
223         {
224                 /* There is an address here. */
225                 in_addr addy;
226                 if (inet_pton(AF_INET, addr, &addy) < 1)
227                 {
228                         delete[] servaddr;
229                         return false;
230                 }
231                 ((sockaddr_in*)servaddr)->sin_addr = addy;
232         }
233         else
234         {
235                 /* Bind ipv4 to all */
236                 ((sockaddr_in*)servaddr)->sin_addr.s_addr = htonl(INADDR_ANY);
237         }
238         /* Bind ipv4 port number */
239         ((sockaddr_in*)servaddr)->sin_port = htons(port);
240         size = sizeof(sockaddr_in);
241 #endif
242         ret = SE->Bind(sockfd, servaddr, size);
243         delete[] servaddr;
244
245         if (ret < 0)
246         {
247                 return false;
248         }
249         else
250         {
251                 if (dolisten)
252                 {
253                         if (SE->Listen(sockfd, Config->MaxConn) == -1)
254                         {
255                                 this->Logs->Log("SOCKET",DEFAULT,"ERROR in listen(): %s",strerror(errno));
256                                 return false;
257                         }
258                         else
259                         {
260                                 this->Logs->Log("SOCKET",DEBUG,"New socket binding for %d with listen: %s:%d", sockfd, addr, port);
261                                 SE->NonBlocking(sockfd);
262                                 return true;
263                         }
264                 }
265                 else
266                 {
267                         this->Logs->Log("SOCKET",DEBUG,"New socket binding for %d without listen: %s:%d", sockfd, addr, port);
268                         return true;
269                 }
270         }
271 }
272
273 // Open a TCP Socket
274 int irc::sockets::OpenTCPSocket(char* addr, int socktype)
275 {
276         int sockfd;
277         int on = 1;
278         addr = addr;
279         struct linger linger = { 0, 0 };
280 #ifdef IPV6
281         if (strchr(addr,':') || (!*addr))
282                 sockfd = socket (PF_INET6, socktype, 0);
283         else
284                 sockfd = socket (PF_INET, socktype, 0);
285         if (sockfd < 0)
286 #else
287         if ((sockfd = socket (PF_INET, socktype, 0)) < 0)
288 #endif
289         {
290                 return ERROR;
291         }
292         else
293         {
294                 setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char*)&on, sizeof(on));
295                 /* This is BSD compatible, setting l_onoff to 0 is *NOT* http://web.irc.org/mla/ircd-dev/msg02259.html */
296                 linger.l_onoff = 1;
297                 linger.l_linger = 1;
298                 setsockopt(sockfd, SOL_SOCKET, SO_LINGER, (char*)&linger,sizeof(linger));
299                 return (sockfd);
300         }
301 }
302
303 int InspIRCd::BindPorts(bool, int &ports_found, FailedPortList &failed_ports)
304 {
305         char configToken[MAXBUF], Addr[MAXBUF], Type[MAXBUF];
306         int bound = 0;
307         bool started_with_nothing = (Config->ports.size() == 0);
308         std::vector<std::pair<std::string, int> > old_ports;
309
310         /* XXX: Make a copy of the old ip/port pairs here */
311         for (std::vector<ListenSocket*>::iterator o = Config->ports.begin(); o != Config->ports.end(); ++o)
312                 old_ports.push_back(make_pair((*o)->GetIP(), (*o)->GetPort()));
313
314         for (int count = 0; count < Config->ConfValueEnum(Config->config_data, "bind"); count++)
315         {
316                 Config->ConfValue(Config->config_data, "bind", "port", count, configToken, MAXBUF);
317                 Config->ConfValue(Config->config_data, "bind", "address", count, Addr, MAXBUF);
318                 Config->ConfValue(Config->config_data, "bind", "type", count, Type, MAXBUF);
319                 
320                 if (strncmp(Addr, "::ffff:", 7) == 0)
321                         this->Logs->Log("SOCKET",DEFAULT, "Using 4in6 (::ffff:) isn't recommended. You should bind IPv4 addresses directly instead.");
322                 
323                 if ((!*Type) || (!strcmp(Type,"clients")))
324                 {
325                         irc::portparser portrange(configToken, false);
326                         int portno = -1;
327                         while (0 != (portno = portrange.GetToken()))
328                         {
329                                 if (*Addr == '*')
330                                         *Addr = 0;
331
332                                 bool skip = false;
333                                 for (std::vector<ListenSocket*>::iterator n = Config->ports.begin(); n != Config->ports.end(); ++n)
334                                 {
335                                         if (((*n)->GetIP() == Addr) && ((*n)->GetPort() == portno))
336                                         {
337                                                 skip = true;
338                                                 /* XXX: Here, erase from our copy of the list */
339                                                 for (std::vector<std::pair<std::string, int> >::iterator k = old_ports.begin(); k != old_ports.end(); ++k)
340                                                 {
341                                                         if ((k->first == Addr) && (k->second == portno))
342                                                         {
343                                                                 old_ports.erase(k);
344                                                                 break;
345                                                         }
346                                                 }
347                                         }
348                                 }
349                                 if (!skip)
350                                 {
351                                         ListenSocket* ll = new ListenSocket(this, portno, Addr);
352                                         if (ll->GetFd() > -1)
353                                         {
354                                                 bound++;
355                                                 Config->ports.push_back(ll);
356                                         }
357                                         else
358                                         {
359                                                 failed_ports.push_back(std::make_pair(Addr, portno));
360                                         }
361                                         ports_found++;
362                                 }
363                         }
364                 }
365         }
366
367         /* XXX: Here, anything left in our copy list, close as removed */
368         if (!started_with_nothing)
369         {
370                 for (size_t k = 0; k < old_ports.size(); ++k)
371                 {
372                         for (std::vector<ListenSocket*>::iterator n = Config->ports.begin(); n != Config->ports.end(); ++n)
373                         {
374                                 if (((*n)->GetIP() == old_ports[k].first) && ((*n)->GetPort() == old_ports[k].second))
375                                 {
376                                         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);
377                                         delete *n;
378                                         Config->ports.erase(n);
379                                         break;
380                                 }
381                         }
382                 }
383         }
384
385         return bound;
386 }
387
388 const char* irc::sockets::insp_ntoa(insp_inaddr n)
389 {
390         static char buf[1024];
391         inet_ntop(AF_FAMILY, &n, buf, sizeof(buf));
392         return buf;
393 }
394
395 int irc::sockets::insp_aton(const char* a, insp_inaddr* n)
396 {
397         return inet_pton(AF_FAMILY, a, n);
398 }
399
400