*** VERSION 5.4.0 ***
[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->flags = 0;
78     client->bufferpos = 0;
79     client->traffic_in = 0;
80     client->traffic_out = 0;
81     client->connection_time = 0;
82         client->botid = 0;
83     client->clientid = 0;
84     client->queue = NULL;
85     client->whoqueue_first = NULL;
86     client->whoqueue_last = NULL;
87     client->handleinfo_first = NULL;
88     client->handleinfo_last = NULL;
89     SYNCHRONIZE(synchronized);
90     client->next = sockets->data;
91     sockets->data = client;
92     DESYNCHRONIZE(synchronized);
93     return client;
94 }
95
96 static int _connect_socket(struct ClientSocket *client);
97
98 int connect_socket(struct ClientSocket *client) {
99     SYNCHRONIZE(synchronized);
100     int ret = _connect_socket(client);
101     DESYNCHRONIZE(synchronized);
102     return ret;
103 }
104
105 #ifndef WIN32
106 static int _connect_socket(struct ClientSocket *client) {
107     if((client->flags & SOCKET_FLAG_CONNECTED)) return 1;
108     int sock;
109     
110     struct addrinfo hints, *res;
111     struct sockaddr_in *ip4 = NULL;
112     struct sockaddr_in6 *ip6 = NULL;
113     memset (&hints, 0, sizeof (hints));
114     hints.ai_family = PF_UNSPEC;
115     hints.ai_socktype = SOCK_STREAM;
116     hints.ai_flags |= AI_CANONNAME;
117     if (getaddrinfo (client->host, NULL, &hints, &res)) {
118         return 0;
119     }
120     while (res) {
121         switch (res->ai_family) {
122         case AF_INET:
123             ip4 = (struct sockaddr_in *) res->ai_addr;
124             break;
125         case AF_INET6:
126             ip6 = (struct sockaddr_in6 *) res->ai_addr;
127             break;
128         }
129         res = res->ai_next;
130     }
131     
132     if(ip6) {
133         sock = socket(AF_INET6, SOCK_STREAM, 0);
134         if(sock == -1) {
135             perror("socket() failed");
136             return 0;
137         }
138         
139         ip6->sin6_family = AF_INET6;
140         ip6->sin6_port = htons(client->port);
141         
142         struct sockaddr_in6 *ip6vhost = NULL;
143         if (client->bind && !getaddrinfo(client->bind, NULL, &hints, &res)) {
144             while (res) {
145                 switch (res->ai_family) {
146                 case AF_INET6:
147                     ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
148                     break;
149                 }
150                 res = res->ai_next;
151             }
152         }
153         if(ip6vhost) {
154             ip6vhost->sin6_family = AF_INET6;
155             ip6vhost->sin6_port = htons(0);
156             bind(sock, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
157         }
158         
159         if (connect(sock, (struct sockaddr*)ip6, sizeof(*ip6)) == -1) {
160             perror("connect() failed");
161             return 0;
162         }
163         
164     } else if(ip4) {
165         sock = socket(AF_INET, SOCK_STREAM, 0);
166         if(sock == -1) {
167             perror("socket() failed");
168             return 0;
169         }
170         
171         ip4->sin_family = AF_INET;
172         ip4->sin_port = htons(client->port);
173         
174         struct sockaddr_in *ip4vhost = NULL;
175         if (client->bind && !getaddrinfo(client->bind, NULL, &hints, &res)) {
176             while (res) {
177                 switch (res->ai_family) {
178                 case AF_INET:
179                     ip4vhost = (struct sockaddr_in *) res->ai_addr;
180                     break;
181                 }
182                 res = res->ai_next;
183             }
184         }
185         if(ip4vhost) {
186             ip4vhost->sin_family = AF_INET;
187             ip4vhost->sin_port = htons(0);
188             bind(sock, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
189         }
190         
191         if (connect(sock, (struct sockaddr*)ip4, sizeof(*ip4)) == -1) {
192             perror("connect() failed");
193             return 0;
194         }
195         
196     } else
197         return 0;
198     
199     if(get_int_field("Sockets.NoDelay")) {
200         int flag = 1;
201         if(setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) == -1) {
202             perror("setsockopt() failed");
203             return 0;
204         }
205     }
206     
207     client->sock = sock;
208     client->flags |= SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT;
209     client->connection_time = time(0);
210     
211     if(client->flags & SOCKET_FLAG_SSL) {
212         ssl_connect(client);
213         client->flags |= SOCKET_FLAG_HAVE_SSL;
214     } else
215         client->flags &= ~SOCKET_FLAG_HAVE_SSL;
216     
217     //send the IRC Headers
218     char sendBuf[512];
219     int len;
220     
221     if(client->pass && strcmp(client->pass, "")) {
222         len = sprintf(sendBuf, "PASS :%s\n", client->pass);
223         write_socket(client, sendBuf, len);
224     }
225     len = sprintf(sendBuf, "USER %s 0 0 :%s\n", client->ident, client->realname);
226     write_socket(client, sendBuf, len);
227     len = sprintf(sendBuf, "NICK %s\n", client->nick);
228     write_socket(client, sendBuf, len);
229     
230     return 1;
231 }
232 #else
233 static int _connect_socket(struct ClientSocket *client) {
234     if((client->flags & SOCKET_FLAG_CONNECTED)) return 1;
235     struct hostent *host;
236     struct sockaddr_in addr;
237     int sock;
238     addr.sin_addr.s_addr = inet_addr(client->host);
239     if (addr.sin_addr.s_addr == INADDR_NONE) {
240         host = gethostbyname(client->host);
241         if(!host) {
242             return SOCKET_ERROR;
243         }
244         memcpy(&(addr.sin_addr), host->h_addr_list[0], 4);
245     }
246     sock = socket(PF_INET, SOCK_STREAM, 0);
247     if (sock == -1)
248     {
249         perror("socket() failed");
250         return 0;
251     }
252
253     addr.sin_port = htons(client->port);
254     addr.sin_family = AF_INET;
255
256     if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1)
257     {
258         perror("connect() failed");
259         return 0;
260     }
261
262     client->sock = sock;
263     client->flags |= SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT;
264     client->connection_time = time(0);
265
266
267     if(client->flags & SOCKET_FLAG_SSL) {
268         ssl_connect(client);
269         client->flags |= SOCKET_FLAG_HAVE_SSL;
270     } else
271         client->flags &= ~SOCKET_FLAG_HAVE_SSL;
272
273     //send the IRC Headers
274     char sendBuf[512];
275     int len;
276
277     if(client->pass && strcmp(client->pass, "")) {
278         len = sprintf(sendBuf, "PASS :%s\n", client->pass);
279         write_socket(client, sendBuf, len);
280     }
281     len = sprintf(sendBuf, "USER %s 0 0 :%s\n", client->ident, client->realname);
282     write_socket(client, sendBuf, len);
283     len = sprintf(sendBuf, "NICK %s\n", client->nick);
284     write_socket(client, sendBuf, len);
285
286     return 1;
287 }
288 #endif
289
290 int close_socket(struct ClientSocket *client) {
291     if(client == NULL) return 0;
292     if((client->flags & SOCKET_FLAG_CONNECTED)) {
293         char quitbuf[MAXLEN];
294         int quitlen = sprintf(quitbuf, "QUIT :[NeonServ %s.%d] disconnect requested.\n", NEONSERV_VERSION, patchlevel);
295         write_socket_force(client, quitbuf, quitlen);
296     }
297     client->flags &= ~(SOCKET_FLAG_READY | SOCKET_FLAG_RECONNECT);
298     client->flags |= SOCKET_FLAG_QUITTED | SOCKET_FLAG_DEAD;
299     return 1;
300 }
301
302 int disconnect_socket(struct ClientSocket *client) {
303     if(client == NULL) return 0;
304     if((client->flags & SOCKET_FLAG_CONNECTED)) {
305         char quitbuf[MAXLEN];
306         int quitlen = sprintf(quitbuf, "QUIT :[NeonServ %s.%d] disconnect requested.\n", NEONSERV_VERSION, patchlevel);
307         write_socket_force(client, quitbuf, quitlen);
308     }
309     client->flags &= ~(SOCKET_FLAG_READY | SOCKET_FLAG_RECONNECT);
310     client->flags |= SOCKET_FLAG_QUITTED;
311     return 1;
312 }
313
314 static void destroy_socket(struct ClientSocket *client, int free_socket) {
315     SYNCHRONIZE(synchronized);
316     if((client->flags & SOCKET_FLAG_CONNECTED)) {
317         close(client->sock);
318         bot_disconnect(client);
319     }
320     if(client->flags & SOCKET_FLAG_HAVE_SSL)
321         ssl_disconnect(client);
322     if(client->queue)
323         queue_destroy(client);
324     if(client->whoqueue_first)
325         clear_whoqueue(client);
326     if(client->handleinfo_first)
327         clear_handleinfoqueue(client);
328     client->flags &= ~(SOCKET_FLAG_CONNECTED | SOCKET_FLAG_READY | SOCKET_FLAG_HAVE_SSL);
329     if(free_socket) {
330         struct ClientSocket *sock, *last_sock = NULL;
331         for (sock = sockets->data; sock; sock = sock->next) {
332             if(sock == client) {
333                 if(last_sock)
334                     last_sock->next = sock->next;
335                 else
336                     sockets->data = sock->next;
337                 sockets->count--;
338                 break;
339             } else
340                 last_sock = sock;
341         }
342         free(client->host);
343         if(client->bind)
344             free(client->bind);
345         if(client->pass)
346             free(client->pass);
347         free(client);
348     } else if(client->flags & SOCKET_FLAG_FAST_JUMP) {
349         client->flags &= ~SOCKET_FLAG_FAST_JUMP;
350         connect_socket(client);
351     }
352     DESYNCHRONIZE(synchronized);
353 }
354
355 int write_socket_force(struct ClientSocket *client, char* msg, int len) {
356     SYNCHRONIZE(synchronized);
357     #ifdef HAVE_THREADS
358     putlog(LOGLEVEL_RAW, "[%d send %d] %s", getCurrentThreadID(), len, msg);
359     #else
360     putlog(LOGLEVEL_RAW, "[send %d] %s", len, msg);
361     #endif
362     if(!(client->flags & SOCKET_FLAG_HAVE_SSL) || ssl_write(client, msg, len) == -2) {
363         #ifdef WIN32
364         send(client->sock, msg, len, 0);
365         #else
366         write(client->sock, msg, len);
367         #endif
368     }
369     client->traffic_out += len;
370     DESYNCHRONIZE(synchronized);
371     return 1;
372 }
373
374 int write_socket(struct ClientSocket *client, char* msg, int len) {
375     if(!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return 0;
376     if(client->flags & SOCKET_FLAG_USE_QUEUE)
377         return queue_add(client, msg, len);
378     else
379         return write_socket_force(client, msg, len);
380 }
381
382 #if HAVE_THREADS
383 static void clientsocket_start_of_recv(unsigned int tid) {
384     SYNCHRONIZE(whohandler_sync);
385     struct ParseOrder *entry, *last;
386     for(last = parse_order; last; last = last->next) {
387         if(last->next == NULL)
388             break;
389     }
390     entry = malloc(sizeof(*entry));
391     entry->tid = tid;
392     entry->next = NULL;
393     if(last)
394         last->next = entry;
395     else
396         parse_order = entry;
397     DESYNCHRONIZE(whohandler_sync);
398 }
399
400 static void clientsocket_end_of_recv(unsigned int tid) {
401     SYNCHRONIZE(whohandler_sync);
402     struct ParseOrder *entry, *last = NULL;
403     for(entry = parse_order; entry; entry = entry->next) {
404         if(entry->tid == tid) {
405             if(last)
406                 last->next = entry->next;
407             else
408                 parse_order = entry->next;
409             free(entry);
410             break;
411         } else
412             last = entry;
413     }
414     DESYNCHRONIZE(whohandler_sync);
415 }
416
417 int clientsocket_parseorder_top(unsigned int tid) {
418     if(parse_order && parse_order->tid == tid)
419         return 1;
420     else
421         return 0;
422 }
423 #endif
424
425 int socket_loop(int timeout_seconds) {
426     if(sockets == NULL) return 0;
427     int is_synchronized = 1;
428     SYNCHRONIZE(synchronized_recv);
429     fd_set fds;
430     struct timeval timeout;
431     struct ClientSocket *sock, *next;
432     int ret = 0, bytes, i;
433     
434     FD_ZERO(&fds);
435     for (sock = sockets->data; sock; sock = sock->next) {
436         if(!(sock->flags & SOCKET_FLAG_CONNECTED)) continue; //skip disconnected sockets
437         FD_SET(sock->sock, &fds);
438         if(sock->sock > ret)
439             ret = sock->sock;
440     }
441     timeout.tv_sec = timeout_seconds;
442     timeout.tv_usec = 0;
443     ret = select(ret + 1, &fds, NULL, NULL, &timeout);
444     if(ret == 0) {
445         DESYNCHRONIZE(synchronized_recv);
446         return 1;
447     }
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 (ret + 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         free(client);
584     }
585     free(sockets);
586     sockets = NULL;
587 }