added stats module for neonserv.krypton-bouncer.de stats
[NeonServV5.git] / src / ClientSocket.c
1 /* ClientSocket.c - NeonServ v5.4
2  * Copyright (C) 2011-2012  Philipp Kreil (pk910)
3  * 
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License 
15  * along with this program. If not, see <http://www.gnu.org/licenses/>. 
16  */
17
18 #include "ClientSocket.h"
19 #include "IRCParser.h"
20 #include "UserNode.h"
21 #include "IRCQueue.h"
22 #include "WHOHandler.h"
23 #include "HandleInfoHandler.h"
24 #include "ssl.h"
25 #include "ConfigParser.h"
26 #include "version.h"
27
28 struct socket_list {
29     struct ClientSocket *data;
30     unsigned count;
31 };
32
33 #ifdef HAVE_THREADS
34 static pthread_mutex_t synchronized;
35 static pthread_mutex_t synchronized_recv;
36
37 struct ParseOrder {
38     unsigned int tid;
39     struct ParseOrder *next;
40 };
41 struct ParseOrder *parse_order = NULL;
42 #endif
43
44 //the magic list :P
45 static struct socket_list *sockets = NULL;
46 static char buffer[BUF_SIZ];
47
48 void init_sockets() {
49     THREAD_MUTEX_INIT(synchronized);
50     THREAD_MUTEX_INIT(synchronized_recv);
51     
52     sockets = malloc(sizeof(*sockets));
53     if (!sockets)
54     {
55         perror("malloc() failed");
56         return;
57     }
58     sockets->data = NULL;
59     sockets->count = 0;
60 }
61
62 struct ClientSocket* create_socket(char *host, int port, char *bindto, char *pass, char *nick, char *ident, char *realname) {
63     struct ClientSocket *client = malloc(sizeof(*client));
64     if (!client)
65     {
66         perror("malloc() failed");
67         return NULL;
68     }
69     client->host = strdup(host);
70     client->port = port;
71     client->bind = (bindto ? strdup(bindto) : NULL);
72     client->pass = (pass == NULL ? NULL : strdup(pass));
73     client->nick = strdup(nick);
74     client->ident = strdup(ident);
75     client->realname = strdup(realname);
76     client->user = NULL;
77     client->network_name = NULL;
78     client->flags = 0;
79     client->bufferpos = 0;
80     client->traffic_in = 0;
81     client->traffic_out = 0;
82     client->connection_time = 0;
83         client->botid = 0;
84     client->clientid = 0;
85     client->queue = NULL;
86     client->whoqueue_first = NULL;
87     client->whoqueue_last = NULL;
88     client->handleinfo_first = NULL;
89     client->handleinfo_last = NULL;
90     SYNCHRONIZE(synchronized);
91     client->next = sockets->data;
92     sockets->data = client;
93     DESYNCHRONIZE(synchronized);
94     return client;
95 }
96
97 static int _connect_socket(struct ClientSocket *client);
98
99 int connect_socket(struct ClientSocket *client) {
100     SYNCHRONIZE(synchronized);
101     int ret = _connect_socket(client);
102     DESYNCHRONIZE(synchronized);
103     return ret;
104 }
105
106 #ifndef WIN32
107 static int _connect_socket(struct ClientSocket *client) {
108     if((client->flags & SOCKET_FLAG_CONNECTED)) return 1;
109     int sock;
110     
111     struct addrinfo hints, *res;
112     struct sockaddr_in *ip4 = NULL;
113     struct sockaddr_in6 *ip6 = NULL;
114     memset (&hints, 0, sizeof (hints));
115     hints.ai_family = PF_UNSPEC;
116     hints.ai_socktype = SOCK_STREAM;
117     hints.ai_flags |= AI_CANONNAME;
118     if (getaddrinfo (client->host, NULL, &hints, &res)) {
119         return 0;
120     }
121     while (res) {
122         switch (res->ai_family) {
123         case AF_INET:
124             ip4 = (struct sockaddr_in *) res->ai_addr;
125             break;
126         case AF_INET6:
127             ip6 = (struct sockaddr_in6 *) res->ai_addr;
128             break;
129         }
130         res = res->ai_next;
131     }
132     
133     if(ip6) {
134         sock = socket(AF_INET6, SOCK_STREAM, 0);
135         if(sock == -1) {
136             perror("socket() failed");
137             return 0;
138         }
139         
140         ip6->sin6_family = AF_INET6;
141         ip6->sin6_port = htons(client->port);
142         
143         struct sockaddr_in6 *ip6vhost = NULL;
144         if (client->bind && !getaddrinfo(client->bind, NULL, &hints, &res)) {
145             while (res) {
146                 switch (res->ai_family) {
147                 case AF_INET6:
148                     ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
149                     break;
150                 }
151                 res = res->ai_next;
152             }
153         }
154         if(ip6vhost) {
155             ip6vhost->sin6_family = AF_INET6;
156             ip6vhost->sin6_port = htons(0);
157             bind(sock, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
158         }
159         
160         if (connect(sock, (struct sockaddr*)ip6, sizeof(*ip6)) == -1) {
161             perror("connect() failed");
162             return 0;
163         }
164         
165     } else if(ip4) {
166         sock = socket(AF_INET, SOCK_STREAM, 0);
167         if(sock == -1) {
168             perror("socket() failed");
169             return 0;
170         }
171         
172         ip4->sin_family = AF_INET;
173         ip4->sin_port = htons(client->port);
174         
175         struct sockaddr_in *ip4vhost = NULL;
176         if (client->bind && !getaddrinfo(client->bind, NULL, &hints, &res)) {
177             while (res) {
178                 switch (res->ai_family) {
179                 case AF_INET:
180                     ip4vhost = (struct sockaddr_in *) res->ai_addr;
181                     break;
182                 }
183                 res = res->ai_next;
184             }
185         }
186         if(ip4vhost) {
187             ip4vhost->sin_family = AF_INET;
188             ip4vhost->sin_port = htons(0);
189             bind(sock, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
190         }
191         
192         if (connect(sock, (struct sockaddr*)ip4, sizeof(*ip4)) == -1) {
193             perror("connect() failed");
194             return 0;
195         }
196         
197     } else
198         return 0;
199     
200     if(get_int_field("Sockets.NoDelay")) {
201         int flag = 1;
202         if(setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) == -1) {
203             perror("setsockopt() failed");
204             return 0;
205         }
206     }
207     
208     client->sock = sock;
209     client->flags |= SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT;
210     client->connection_time = time(0);
211     
212     if(client->flags & SOCKET_FLAG_SSL) {
213         ssl_connect(client);
214         client->flags |= SOCKET_FLAG_HAVE_SSL;
215     } else
216         client->flags &= ~SOCKET_FLAG_HAVE_SSL;
217     
218     //send the IRC Headers
219     char sendBuf[512];
220     int len;
221     
222     if(client->pass && strcmp(client->pass, "")) {
223         len = sprintf(sendBuf, "PASS :%s\n", client->pass);
224         write_socket(client, sendBuf, len);
225     }
226     len = sprintf(sendBuf, "USER %s 0 0 :%s\n", client->ident, client->realname);
227     write_socket(client, sendBuf, len);
228     len = sprintf(sendBuf, "NICK %s\n", client->nick);
229     write_socket(client, sendBuf, len);
230     
231     return 1;
232 }
233 #else
234 static int _connect_socket(struct ClientSocket *client) {
235     if((client->flags & SOCKET_FLAG_CONNECTED)) return 1;
236     struct hostent *host;
237     struct sockaddr_in addr;
238     int sock;
239     addr.sin_addr.s_addr = inet_addr(client->host);
240     if (addr.sin_addr.s_addr == INADDR_NONE) {
241         host = gethostbyname(client->host);
242         if(!host) {
243             return SOCKET_ERROR;
244         }
245         memcpy(&(addr.sin_addr), host->h_addr_list[0], 4);
246     }
247     sock = socket(PF_INET, SOCK_STREAM, 0);
248     if (sock == -1)
249     {
250         perror("socket() failed");
251         return 0;
252     }
253
254     addr.sin_port = htons(client->port);
255     addr.sin_family = AF_INET;
256
257     if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1)
258     {
259         perror("connect() failed");
260         return 0;
261     }
262
263     client->sock = sock;
264     client->flags |= SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT;
265     client->connection_time = time(0);
266
267
268     if(client->flags & SOCKET_FLAG_SSL) {
269         ssl_connect(client);
270         client->flags |= SOCKET_FLAG_HAVE_SSL;
271     } else
272         client->flags &= ~SOCKET_FLAG_HAVE_SSL;
273
274     //send the IRC Headers
275     char sendBuf[512];
276     int len;
277
278     if(client->pass && strcmp(client->pass, "")) {
279         len = sprintf(sendBuf, "PASS :%s\n", client->pass);
280         write_socket(client, sendBuf, len);
281     }
282     len = sprintf(sendBuf, "USER %s 0 0 :%s\n", client->ident, client->realname);
283     write_socket(client, sendBuf, len);
284     len = sprintf(sendBuf, "NICK %s\n", client->nick);
285     write_socket(client, sendBuf, len);
286
287     return 1;
288 }
289 #endif
290
291 int close_socket(struct ClientSocket *client) {
292     if(client == NULL) return 0;
293     if((client->flags & SOCKET_FLAG_CONNECTED)) {
294         char quitbuf[MAXLEN];
295         int quitlen = sprintf(quitbuf, "QUIT :[NeonServ %s.%d] disconnect requested.\n", NEONSERV_VERSION, patchlevel);
296         write_socket_force(client, quitbuf, quitlen);
297     }
298     client->flags &= ~(SOCKET_FLAG_READY | SOCKET_FLAG_RECONNECT);
299     client->flags |= SOCKET_FLAG_QUITTED | SOCKET_FLAG_DEAD;
300     return 1;
301 }
302
303 int disconnect_socket(struct ClientSocket *client) {
304     if(client == NULL) return 0;
305     if((client->flags & SOCKET_FLAG_CONNECTED)) {
306         char quitbuf[MAXLEN];
307         int quitlen = sprintf(quitbuf, "QUIT :[NeonServ %s.%d] disconnect requested.\n", NEONSERV_VERSION, patchlevel);
308         write_socket_force(client, quitbuf, quitlen);
309     }
310     client->flags &= ~(SOCKET_FLAG_READY | SOCKET_FLAG_RECONNECT);
311     client->flags |= SOCKET_FLAG_QUITTED;
312     return 1;
313 }
314
315 static void destroy_socket(struct ClientSocket *client, int free_socket) {
316     SYNCHRONIZE(synchronized);
317     if((client->flags & SOCKET_FLAG_CONNECTED)) {
318         close(client->sock);
319         bot_disconnect(client);
320     }
321     if(client->flags & SOCKET_FLAG_HAVE_SSL)
322         ssl_disconnect(client);
323     if(client->queue)
324         queue_destroy(client);
325     if(client->whoqueue_first)
326         clear_whoqueue(client);
327     if(client->handleinfo_first)
328         clear_handleinfoqueue(client);
329     client->flags &= ~(SOCKET_FLAG_CONNECTED | SOCKET_FLAG_READY | SOCKET_FLAG_HAVE_SSL);
330     if(free_socket) {
331         struct ClientSocket *sock, *last_sock = NULL;
332         for (sock = sockets->data; sock; sock = sock->next) {
333             if(sock == client) {
334                 if(last_sock)
335                     last_sock->next = sock->next;
336                 else
337                     sockets->data = sock->next;
338                 sockets->count--;
339                 break;
340             } else
341                 last_sock = sock;
342         }
343         free(client->host);
344         if(client->bind)
345             free(client->bind);
346         if(client->pass)
347             free(client->pass);
348         if(client->network_name)
349             free(client->network_name);
350         free(client);
351     } else if(client->flags & SOCKET_FLAG_FAST_JUMP) {
352         client->flags &= ~SOCKET_FLAG_FAST_JUMP;
353         connect_socket(client);
354     }
355     DESYNCHRONIZE(synchronized);
356 }
357
358 int write_socket_force(struct ClientSocket *client, char* msg, int len) {
359     SYNCHRONIZE(synchronized);
360     #ifdef HAVE_THREADS
361     putlog(LOGLEVEL_RAW, "[%d send %d] %s", getCurrentThreadID(), len, msg);
362     #else
363     putlog(LOGLEVEL_RAW, "[send %d] %s", len, msg);
364     #endif
365     if(!(client->flags & SOCKET_FLAG_HAVE_SSL) || ssl_write(client, msg, len) == -2) {
366         #ifdef WIN32
367         send(client->sock, msg, len, 0);
368         #else
369         write(client->sock, msg, len);
370         #endif
371     }
372     client->traffic_out += len;
373     DESYNCHRONIZE(synchronized);
374     return 1;
375 }
376
377 int write_socket(struct ClientSocket *client, char* msg, int len) {
378     if(!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return 0;
379     if(client->flags & SOCKET_FLAG_USE_QUEUE)
380         return queue_add(client, msg, len);
381     else
382         return write_socket_force(client, msg, len);
383 }
384
385 #if HAVE_THREADS
386 static void clientsocket_start_of_recv(unsigned int tid) {
387     SYNCHRONIZE(whohandler_sync);
388     struct ParseOrder *entry, *last;
389     for(last = parse_order; last; last = last->next) {
390         if(last->next == NULL)
391             break;
392     }
393     entry = malloc(sizeof(*entry));
394     entry->tid = tid;
395     entry->next = NULL;
396     if(last)
397         last->next = entry;
398     else
399         parse_order = entry;
400     DESYNCHRONIZE(whohandler_sync);
401 }
402
403 static void clientsocket_end_of_recv(unsigned int tid) {
404     SYNCHRONIZE(whohandler_sync);
405     struct ParseOrder *entry, *last = NULL;
406     for(entry = parse_order; entry; entry = entry->next) {
407         if(entry->tid == tid) {
408             if(last)
409                 last->next = entry->next;
410             else
411                 parse_order = entry->next;
412             free(entry);
413             break;
414         } else
415             last = entry;
416     }
417     DESYNCHRONIZE(whohandler_sync);
418 }
419
420 int clientsocket_parseorder_top(unsigned int tid) {
421     if(parse_order && parse_order->tid == tid)
422         return 1;
423     else
424         return 0;
425 }
426 #endif
427
428 int socket_loop(int timeout_seconds) {
429     if(sockets == NULL) return 0;
430     int is_synchronized = 1;
431     SYNCHRONIZE(synchronized_recv);
432     fd_set fds;
433     struct timeval timeout;
434     struct ClientSocket *sock, *next;
435     int ret = 0, bytes, i;
436     
437     FD_ZERO(&fds);
438     for (sock = sockets->data; sock; sock = sock->next) {
439         if(!(sock->flags & SOCKET_FLAG_CONNECTED)) continue; //skip disconnected sockets
440         FD_SET(sock->sock, &fds);
441         if(sock->sock > ret)
442             ret = sock->sock;
443     }
444     timeout.tv_sec = timeout_seconds;
445     timeout.tv_usec = 0;
446     ret = select(ret + 1, &fds, NULL, NULL, &timeout);
447     if(ret == 0) {
448         DESYNCHRONIZE(synchronized_recv);
449         return 1;
450     }
451     for (sock = sockets->data; sock; sock = next) {
452         next = sock->next;
453         if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_QUITTED)) == SOCKET_FLAG_CONNECTED && FD_ISSET(sock->sock, &fds)) {
454             if(sock->bufferpos != 0) {
455                 if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, buffer, sizeof(buffer))) == -2) {
456                     #ifdef WIN32
457                     bytes = recv(sock->sock, buffer, sizeof(buffer), 0);
458                     #else
459                     bytes = read(sock->sock, buffer, sizeof(buffer));
460                     #endif
461                 }
462                 if(bytes > 0) {
463                     for(i = 0; i < bytes; i++) {
464                         if(sock->bufferpos + i == BUF_SIZ*2) break; //buffer overflow
465                         sock->buffer[sock->bufferpos + i] = buffer[i];
466                     }
467                     sock->bufferpos += i;
468                 }
469             } else {
470                 if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, sock->buffer, sizeof(sock->buffer))) == -2) {
471                     #ifdef WIN32
472                     bytes = recv(sock->sock, sock->buffer, sizeof(sock->buffer), 0);
473                     #else
474                     bytes = read(sock->sock, sock->buffer, sizeof(sock->buffer));
475                     #endif
476                 }
477                 if(bytes > 0)
478                     sock->bufferpos = bytes;
479             }
480             if(bytes <= 0) {
481                 //error
482                 sock->flags |= SOCKET_FLAG_QUITTED;
483             } else {
484                 sock->traffic_in += bytes;
485                 #ifdef HAVE_THREADS
486                 char linesbuf[BUF_SIZ*2];
487                 strcpy(linesbuf, sock->buffer);
488                 int used = 0;
489                 for(i = 0; i < sock->bufferpos; i++) {
490                     if(sock->buffer[i] == '\n') {
491                         used = i+1;
492                     }
493                 }
494                 if(used == sock->bufferpos + 1) {
495                     //used all bytes so just reset the bufferpos
496                     sock->bufferpos = 0;
497                 } else {
498                     for(i = 0; i < sock->bufferpos - used; i++) {
499                         sock->buffer[i] = sock->buffer[i+used];
500                     }
501                     sock->bufferpos -= used;
502                 }
503                 is_synchronized = 0;
504                 unsigned int tid = (unsigned int) pthread_self_tid();
505                 clientsocket_start_of_recv(tid);
506                 DESYNCHRONIZE(synchronized_recv);
507                 parse_lines(sock, linesbuf, used);
508                 clientsocket_end_of_recv(tid);
509                 #else
510                 int used = parse_lines(sock, sock->buffer, sock->bufferpos);
511                 if(used == sock->bufferpos + 1) {
512                     //used all bytes so just reset the bufferpos
513                     sock->bufferpos = 0;
514                 } else {
515                     for(i = 0; i < sock->bufferpos - used; i++) {
516                         sock->buffer[i] = sock->buffer[i+used];
517                     }
518                     sock->bufferpos -= used;
519                 }
520                 is_synchronized = 0;
521                 DESYNCHRONIZE(synchronized_recv);
522                 #endif
523                 #ifdef HAVE_THREADS
524                 FD_ZERO(&fds); //zero out all other pending sockets here (we have other threads receiving from them)
525                 #endif
526             }
527         } else if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT)) == SOCKET_FLAG_RECONNECT) {
528             if(time(0) - sock->connection_time >= SOCKET_RECONNECT_TIME) {
529                 connect_socket(sock);
530             }
531         }
532         if((sock->flags & SOCKET_FLAG_QUITTED)) {
533             sock->flags &= ~SOCKET_FLAG_QUITTED;
534             destroy_socket(sock, (sock->flags & SOCKET_FLAG_DEAD));
535         }
536     }
537     if(is_synchronized) {
538         DESYNCHRONIZE(synchronized_recv);
539     }
540     return (ret + 1);
541 }
542
543 void
544 putsock(struct ClientSocket *client, const char *text, ...)
545 {
546     va_list arg_list;
547     char sendBuf[MAXLEN];
548     int pos;
549     if (!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return;
550     sendBuf[0] = '\0';
551     va_start(arg_list, text);
552     pos = vsnprintf(sendBuf, MAXLEN - 2, text, arg_list);
553     va_end(arg_list);
554     if (pos < 0 || pos > (MAXLEN - 2)) pos = MAXLEN - 2;
555     sendBuf[pos] = '\n';
556     sendBuf[pos+1] = '\0';
557     write_socket(client, sendBuf, pos+1);
558 }
559
560 struct ClientSocket* getBots(int flags, struct ClientSocket* last_bot) {
561     struct ClientSocket *sock = (last_bot ? last_bot->next : sockets->data);
562     if(sock == NULL) return NULL;
563     for (; sock; sock = sock->next) {
564         if(!flags || (sock->flags & flags) == flags)
565             return sock;
566     }
567     return NULL;
568 }
569
570 void free_sockets() {
571     if(!sockets) return;
572     struct ClientSocket *client, *next;
573     for (client = sockets->data; client; client = next) {
574         next = client->next;
575         if((client->flags & SOCKET_FLAG_CONNECTED))
576             close(client->sock);
577         if(client->flags & SOCKET_FLAG_HAVE_SSL)
578             ssl_disconnect(client);
579         if(client->queue)
580             queue_destroy(client);
581         free(client->host);
582         if(client->bind)
583             free(client->bind);
584         if(client->pass)
585             free(client->pass);
586         if(client->network_name)
587             free(client->network_name);
588         free(client);
589     }
590     free(sockets);
591     sockets = NULL;
592 }