*** VERSION 5.5.0 ***
[NeonServV5.git] / src / ClientSocket.c
1 /* ClientSocket.c - NeonServ v5.5
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     client->connection_time = time(0);
110     int sock;
111     
112     struct addrinfo hints, *res;
113     struct sockaddr_in *ip4 = NULL;
114     struct sockaddr_in6 *ip6 = NULL;
115     memset (&hints, 0, sizeof (hints));
116     hints.ai_family = PF_UNSPEC;
117     hints.ai_socktype = SOCK_STREAM;
118     hints.ai_flags |= AI_CANONNAME;
119     if (getaddrinfo (client->host, NULL, &hints, &res)) {
120         return 0;
121     }
122     while (res) {
123         switch (res->ai_family) {
124         case AF_INET:
125             ip4 = (struct sockaddr_in *) res->ai_addr;
126             break;
127         case AF_INET6:
128             ip6 = (struct sockaddr_in6 *) res->ai_addr;
129             break;
130         }
131         res = res->ai_next;
132     }
133     
134     if(ip6) {
135         sock = socket(AF_INET6, SOCK_STREAM, 0);
136         if(sock == -1) {
137             perror("socket() failed");
138             return 0;
139         }
140         
141         ip6->sin6_family = AF_INET6;
142         ip6->sin6_port = htons(client->port);
143         
144         struct sockaddr_in6 *ip6vhost = NULL;
145         if (client->bind && !getaddrinfo(client->bind, NULL, &hints, &res)) {
146             while (res) {
147                 switch (res->ai_family) {
148                 case AF_INET6:
149                     ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
150                     break;
151                 }
152                 res = res->ai_next;
153             }
154         }
155         if(ip6vhost) {
156             ip6vhost->sin6_family = AF_INET6;
157             ip6vhost->sin6_port = htons(0);
158             bind(sock, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
159         }
160         
161         if (connect(sock, (struct sockaddr*)ip6, sizeof(*ip6)) == -1) {
162             perror("connect() failed");
163             return 0;
164         }
165         
166     } else if(ip4) {
167         sock = socket(AF_INET, SOCK_STREAM, 0);
168         if(sock == -1) {
169             perror("socket() failed");
170             return 0;
171         }
172         
173         ip4->sin_family = AF_INET;
174         ip4->sin_port = htons(client->port);
175         
176         struct sockaddr_in *ip4vhost = NULL;
177         if (client->bind && !getaddrinfo(client->bind, NULL, &hints, &res)) {
178             while (res) {
179                 switch (res->ai_family) {
180                 case AF_INET:
181                     ip4vhost = (struct sockaddr_in *) res->ai_addr;
182                     break;
183                 }
184                 res = res->ai_next;
185             }
186         }
187         if(ip4vhost) {
188             ip4vhost->sin_family = AF_INET;
189             ip4vhost->sin_port = htons(0);
190             bind(sock, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
191         }
192         
193         if (connect(sock, (struct sockaddr*)ip4, sizeof(*ip4)) == -1) {
194             perror("connect() failed");
195             return 0;
196         }
197         
198     } else
199         return 0;
200     
201     if(get_int_field("Sockets.NoDelay")) {
202         int flag = 1;
203         if(setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) == -1) {
204             perror("setsockopt() failed");
205             return 0;
206         }
207     }
208     
209     client->sock = sock;
210     client->flags |= SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT;
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     client->connection_time = time(0);
237     struct hostent *host;
238     struct sockaddr_in addr;
239     int sock;
240     addr.sin_addr.s_addr = inet_addr(client->host);
241     if (addr.sin_addr.s_addr == INADDR_NONE) {
242         host = gethostbyname(client->host);
243         if(!host) {
244             return SOCKET_ERROR;
245         }
246         memcpy(&(addr.sin_addr), host->h_addr_list[0], 4);
247     }
248     sock = socket(PF_INET, SOCK_STREAM, 0);
249     if (sock == -1)
250     {
251         perror("socket() failed");
252         return 0;
253     }
254
255     addr.sin_port = htons(client->port);
256     addr.sin_family = AF_INET;
257
258     if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1)
259     {
260         perror("connect() failed");
261         return 0;
262     }
263
264     client->sock = sock;
265     client->flags |= SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT;
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         int ret = 1;
366     if(!(client->flags & SOCKET_FLAG_HAVE_SSL) || ssl_write(client, msg, len) == -2) {
367         #ifdef WIN32
368         ret = send(client->sock, msg, len, 0);
369         #else
370         ret = write(client->sock, msg, len);
371         #endif
372     }
373     client->traffic_out += len;
374     DESYNCHRONIZE(synchronized);
375     return ret;
376 }
377
378 int write_socket(struct ClientSocket *client, char* msg, int len) {
379     if(!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return 0;
380     if(client->flags & SOCKET_FLAG_USE_QUEUE)
381         return queue_add(client, msg, len);
382     else
383         return write_socket_force(client, msg, len);
384 }
385
386 #if HAVE_THREADS
387 static void clientsocket_start_of_recv(unsigned int tid) {
388     SYNCHRONIZE(whohandler_sync);
389     struct ParseOrder *entry, *last;
390     for(last = parse_order; last; last = last->next) {
391         if(last->next == NULL)
392             break;
393     }
394     entry = malloc(sizeof(*entry));
395     entry->tid = tid;
396     entry->next = NULL;
397     if(last)
398         last->next = entry;
399     else
400         parse_order = entry;
401     DESYNCHRONIZE(whohandler_sync);
402 }
403
404 static void clientsocket_end_of_recv(unsigned int tid) {
405     SYNCHRONIZE(whohandler_sync);
406     struct ParseOrder *entry, *last = NULL;
407     for(entry = parse_order; entry; entry = entry->next) {
408         if(entry->tid == tid) {
409             if(last)
410                 last->next = entry->next;
411             else
412                 parse_order = entry->next;
413             free(entry);
414             break;
415         } else
416             last = entry;
417     }
418     DESYNCHRONIZE(whohandler_sync);
419 }
420
421 int clientsocket_parseorder_top(unsigned int tid) {
422     if(parse_order && parse_order->tid == tid)
423         return 1;
424     else
425         return 0;
426 }
427 #endif
428
429 int socket_loop(int timeout_seconds) {
430     if(sockets == NULL) return 0;
431     int is_synchronized = 1;
432     SYNCHRONIZE(synchronized_recv);
433     fd_set fds;
434     struct timeval timeout;
435     struct ClientSocket *sock, *next;
436     int ret = 0, bytes, i;
437     
438     FD_ZERO(&fds);
439     for (sock = sockets->data; sock; sock = sock->next) {
440         if(!(sock->flags & SOCKET_FLAG_CONNECTED)) continue; //skip disconnected sockets
441         FD_SET(sock->sock, &fds);
442         if(sock->sock > ret)
443             ret = sock->sock;
444     }
445     timeout.tv_sec = timeout_seconds;
446     timeout.tv_usec = 0;
447     ret = select(ret + 1, &fds, NULL, NULL, &timeout);
448     for (sock = sockets->data; sock; sock = next) {
449         next = sock->next;
450         if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_QUITTED)) == SOCKET_FLAG_CONNECTED && FD_ISSET(sock->sock, &fds)) {
451             if(sock->bufferpos != 0) {
452                 if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, buffer, sizeof(buffer))) == -2) {
453                     #ifdef WIN32
454                     bytes = recv(sock->sock, buffer, sizeof(buffer), 0);
455                     #else
456                     bytes = read(sock->sock, buffer, sizeof(buffer));
457                     #endif
458                 }
459                 if(bytes > 0) {
460                     for(i = 0; i < bytes; i++) {
461                         if(sock->bufferpos + i == BUF_SIZ*2) break; //buffer overflow
462                         sock->buffer[sock->bufferpos + i] = buffer[i];
463                     }
464                     sock->bufferpos += i;
465                 }
466             } else {
467                 if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, sock->buffer, sizeof(sock->buffer))) == -2) {
468                     #ifdef WIN32
469                     bytes = recv(sock->sock, sock->buffer, sizeof(sock->buffer), 0);
470                     #else
471                     bytes = read(sock->sock, sock->buffer, sizeof(sock->buffer));
472                     #endif
473                 }
474                 if(bytes > 0)
475                     sock->bufferpos = bytes;
476             }
477             if(bytes <= 0) {
478                 //error
479                 sock->flags |= SOCKET_FLAG_QUITTED;
480             } else {
481                 sock->traffic_in += bytes;
482                 #ifdef HAVE_THREADS
483                 char linesbuf[BUF_SIZ*2];
484                 strcpy(linesbuf, sock->buffer);
485                 int used = 0;
486                 for(i = 0; i < sock->bufferpos; i++) {
487                     if(sock->buffer[i] == '\n') {
488                         used = i+1;
489                     }
490                 }
491                 if(used == sock->bufferpos + 1) {
492                     //used all bytes so just reset the bufferpos
493                     sock->bufferpos = 0;
494                 } else {
495                     for(i = 0; i < sock->bufferpos - used; i++) {
496                         sock->buffer[i] = sock->buffer[i+used];
497                     }
498                     sock->bufferpos -= used;
499                 }
500                 is_synchronized = 0;
501                 unsigned int tid = (unsigned int) pthread_self_tid();
502                 clientsocket_start_of_recv(tid);
503                 DESYNCHRONIZE(synchronized_recv);
504                 parse_lines(sock, linesbuf, used);
505                 clientsocket_end_of_recv(tid);
506                 #else
507                 int used = parse_lines(sock, sock->buffer, sock->bufferpos);
508                 if(used == sock->bufferpos + 1) {
509                     //used all bytes so just reset the bufferpos
510                     sock->bufferpos = 0;
511                 } else {
512                     for(i = 0; i < sock->bufferpos - used; i++) {
513                         sock->buffer[i] = sock->buffer[i+used];
514                     }
515                     sock->bufferpos -= used;
516                 }
517                 is_synchronized = 0;
518                 DESYNCHRONIZE(synchronized_recv);
519                 #endif
520                 #ifdef HAVE_THREADS
521                 FD_ZERO(&fds); //zero out all other pending sockets here (we have other threads receiving from them)
522                 #endif
523             }
524         } else if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT)) == SOCKET_FLAG_RECONNECT) {
525             if(time(0) - sock->connection_time >= SOCKET_RECONNECT_TIME) {
526                 connect_socket(sock);
527             }
528         }
529         if((sock->flags & SOCKET_FLAG_QUITTED)) {
530             sock->flags &= ~SOCKET_FLAG_QUITTED;
531             destroy_socket(sock, (sock->flags & SOCKET_FLAG_DEAD));
532         }
533     }
534     if(is_synchronized) {
535         DESYNCHRONIZE(synchronized_recv);
536     }
537     return 1;
538 }
539
540 void
541 putsock(struct ClientSocket *client, const char *text, ...)
542 {
543     va_list arg_list;
544     char sendBuf[MAXLEN];
545     int pos;
546     if (!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return;
547     sendBuf[0] = '\0';
548     va_start(arg_list, text);
549     pos = vsnprintf(sendBuf, MAXLEN - 2, text, arg_list);
550     va_end(arg_list);
551     if (pos < 0 || pos > (MAXLEN - 2)) pos = MAXLEN - 2;
552     sendBuf[pos] = '\n';
553     sendBuf[pos+1] = '\0';
554     write_socket(client, sendBuf, pos+1);
555 }
556
557 struct ClientSocket* getBots(int flags, struct ClientSocket* last_bot) {
558     struct ClientSocket *sock = (last_bot ? last_bot->next : sockets->data);
559     if(sock == NULL) return NULL;
560     for (; sock; sock = sock->next) {
561         if(!flags || (sock->flags & flags) == flags)
562             return sock;
563     }
564     return NULL;
565 }
566
567 void free_sockets() {
568     if(!sockets) return;
569     struct ClientSocket *client, *next;
570     for (client = sockets->data; client; client = next) {
571         next = client->next;
572         if((client->flags & SOCKET_FLAG_CONNECTED))
573             close(client->sock);
574         if(client->flags & SOCKET_FLAG_HAVE_SSL)
575             ssl_disconnect(client);
576         if(client->queue)
577             queue_destroy(client);
578         free(client->host);
579         if(client->bind)
580             free(client->bind);
581         if(client->pass)
582             free(client->pass);
583         if(client->network_name)
584             free(client->network_name);
585         free(client);
586     }
587     free(sockets);
588     sockets = NULL;
589 }