80f4c37d2cae7f73fa4cdd4b996858bfa528d551
[NeonServV5.git] / src / ClientSocket.c
1 /* ClientSocket.c - NeonServ v5.3
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 #endif
37
38 //the magic list :P
39 static struct socket_list *sockets = NULL;
40 static char buffer[BUF_SIZ];
41
42 void init_sockets() {
43     THREAD_MUTEX_INIT(synchronized);
44     THREAD_MUTEX_INIT(synchronized_recv);
45     
46     sockets = malloc(sizeof(*sockets));
47     if (!sockets)
48     {
49         perror("malloc() failed");
50         return;
51     }
52     sockets->data = NULL;
53     sockets->count = 0;
54 }
55
56 struct ClientSocket* create_socket(char *host, int port, char *bindto, char *pass, char *nick, char *ident, char *realname) {
57     struct ClientSocket *client = malloc(sizeof(*client));
58     if (!client)
59     {
60         perror("malloc() failed");
61         return NULL;
62     }
63     client->host = strdup(host);
64     client->port = port;
65     client->bind = (bindto ? strdup(bindto) : NULL);
66     client->pass = (pass == NULL ? NULL : strdup(pass));
67     client->nick = strdup(nick);
68     client->ident = strdup(ident);
69     client->realname = strdup(realname);
70     client->user = NULL;
71     client->flags = 0;
72     client->bufferpos = 0;
73     client->traffic_in = 0;
74     client->traffic_out = 0;
75     client->connection_time = 0;
76         client->botid = 0;
77     client->clientid = 0;
78     client->queue = NULL;
79     client->whoqueue_first = NULL;
80     client->whoqueue_last = NULL;
81     client->handleinfo_first = NULL;
82     client->handleinfo_last = NULL;
83     SYNCHRONIZE(synchronized);
84     client->next = sockets->data;
85     sockets->data = client;
86     DESYNCHRONIZE(synchronized);
87     return client;
88 }
89
90 static int _connect_socket(struct ClientSocket *client);
91
92 int connect_socket(struct ClientSocket *client) {
93     SYNCHRONIZE(synchronized);
94     int ret = _connect_socket(client);
95     DESYNCHRONIZE(synchronized);
96     return ret;
97 }
98
99 #ifndef WIN32
100 static int _connect_socket(struct ClientSocket *client) {
101     if((client->flags & SOCKET_FLAG_CONNECTED)) return 1;
102     int sock;
103     
104     struct addrinfo hints, *res;
105     struct sockaddr_in *ip4 = NULL;
106     struct sockaddr_in6 *ip6 = NULL;
107     memset (&hints, 0, sizeof (hints));
108     hints.ai_family = PF_UNSPEC;
109     hints.ai_socktype = SOCK_STREAM;
110     hints.ai_flags |= AI_CANONNAME;
111     if (getaddrinfo (client->host, NULL, &hints, &res)) {
112         return 0;
113     }
114     while (res) {
115         switch (res->ai_family) {
116         case AF_INET:
117             ip4 = (struct sockaddr_in *) res->ai_addr;
118             break;
119         case AF_INET6:
120             ip6 = (struct sockaddr_in6 *) res->ai_addr;
121             break;
122         }
123         res = res->ai_next;
124     }
125     
126     if(ip6) {
127         sock = socket(AF_INET6, SOCK_STREAM, 0);
128         if(sock == -1) {
129             perror("socket() failed");
130             return 0;
131         }
132         
133         ip6->sin6_family = AF_INET6;
134         ip6->sin6_port = htons(client->port);
135         
136         struct sockaddr_in6 *ip6vhost = NULL;
137         if (client->bind && !getaddrinfo(client->bind, NULL, &hints, &res)) {
138             while (res) {
139                 switch (res->ai_family) {
140                 case AF_INET6:
141                     ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
142                     break;
143                 }
144                 res = res->ai_next;
145             }
146         }
147         if(ip6vhost) {
148             ip6vhost->sin6_family = AF_INET6;
149             ip6vhost->sin6_port = htons(0);
150             bind(sock, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
151         }
152         
153         if (connect(sock, (struct sockaddr*)ip6, sizeof(*ip6)) == -1) {
154             perror("connect() failed");
155             return 0;
156         }
157         
158     } else if(ip4) {
159         sock = socket(AF_INET, SOCK_STREAM, 0);
160         if(sock == -1) {
161             perror("socket() failed");
162             return 0;
163         }
164         
165         ip4->sin_family = AF_INET;
166         ip4->sin_port = htons(client->port);
167         
168         struct sockaddr_in *ip4vhost = NULL;
169         if (client->bind && !getaddrinfo(client->bind, NULL, &hints, &res)) {
170             while (res) {
171                 switch (res->ai_family) {
172                 case AF_INET:
173                     ip4vhost = (struct sockaddr_in *) res->ai_addr;
174                     break;
175                 }
176                 res = res->ai_next;
177             }
178         }
179         if(ip4vhost) {
180             ip4vhost->sin_family = AF_INET;
181             ip4vhost->sin_port = htons(0);
182             bind(sock, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
183         }
184         
185         if (connect(sock, (struct sockaddr*)ip4, sizeof(*ip4)) == -1) {
186             perror("connect() failed");
187             return 0;
188         }
189         
190     } else
191         return 0;
192     
193     if(get_int_field("Sockets.NoDelay")) {
194         int flag = 1;
195         if(setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) == -1) {
196             perror("setsockopt() failed");
197             return 0;
198         }
199     }
200     
201     client->sock = sock;
202     client->flags |= SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT;
203     client->connection_time = time(0);
204     
205     if(client->flags & SOCKET_FLAG_SSL) {
206         ssl_connect(client);
207         client->flags |= SOCKET_FLAG_HAVE_SSL;
208     } else
209         client->flags &= ~SOCKET_FLAG_HAVE_SSL;
210     
211     //send the IRC Headers
212     char sendBuf[512];
213     int len;
214     
215     if(client->pass && strcmp(client->pass, "")) {
216         len = sprintf(sendBuf, "PASS :%s\n", client->pass);
217         write_socket(client, sendBuf, len);
218     }
219     len = sprintf(sendBuf, "USER %s 0 0 :%s\n", client->ident, client->realname);
220     write_socket(client, sendBuf, len);
221     len = sprintf(sendBuf, "NICK %s\n", client->nick);
222     write_socket(client, sendBuf, len);
223     
224     return 1;
225 }
226 #else
227 static int connect_socket(struct ClientSocket *client) {
228     if((client->flags & SOCKET_FLAG_CONNECTED)) return 1;
229     struct hostent *host;
230     struct sockaddr_in addr;
231     int sock;
232     addr.sin_addr.s_addr = inet_addr(client->host);
233     if (addr.sin_addr.s_addr == INADDR_NONE) {
234         host = gethostbyname(client->host);
235         if(!host) {
236             return SOCKET_ERROR;
237         }
238         memcpy(&(addr.sin_addr), host->h_addr_list[0], 4);
239     }
240     sock = socket(PF_INET, SOCK_STREAM, 0);
241     if (sock == -1)
242     {
243         perror("socket() failed");
244         return 0;
245     }
246
247     addr.sin_port = htons(client->port);
248     addr.sin_family = AF_INET;
249
250     if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1)
251     {
252         perror("connect() failed");
253         return 0;
254     }
255
256     client->sock = sock;
257     client->flags |= SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT;
258     client->connection_time = time(0);
259
260
261     if(client->flags & SOCKET_FLAG_SSL) {
262         ssl_connect(client);
263         client->flags |= SOCKET_FLAG_HAVE_SSL;
264     } else
265         client->flags &= ~SOCKET_FLAG_HAVE_SSL;
266
267     //send the IRC Headers
268     char sendBuf[512];
269     int len;
270
271     if(client->pass && strcmp(client->pass, "")) {
272         len = sprintf(sendBuf, "PASS :%s\n", client->pass);
273         write_socket(client, sendBuf, len);
274     }
275     len = sprintf(sendBuf, "USER %s 0 0 :%s\n", client->ident, client->realname);
276     write_socket(client, sendBuf, len);
277     len = sprintf(sendBuf, "NICK %s\n", client->nick);
278     write_socket(client, sendBuf, len);
279
280     return 1;
281 }
282 #endif
283
284 int close_socket(struct ClientSocket *client) {
285     if(client == NULL) return 0;
286     if((client->flags & SOCKET_FLAG_CONNECTED)) {
287         char quitbuf[MAXLEN];
288         int quitlen = sprintf(quitbuf, "QUIT :[NeonServ %s.%d] disconnect requested.\n", NEONSERV_VERSION, patchlevel);
289         write_socket_force(client, quitbuf, quitlen);
290     }
291     client->flags &= ~(SOCKET_FLAG_READY | SOCKET_FLAG_RECONNECT);
292     client->flags |= SOCKET_FLAG_QUITTED | SOCKET_FLAG_DEAD;
293     return 1;
294 }
295
296 int disconnect_socket(struct ClientSocket *client) {
297     if(client == NULL) return 0;
298     if((client->flags & SOCKET_FLAG_CONNECTED)) {
299         char quitbuf[MAXLEN];
300         int quitlen = sprintf(quitbuf, "QUIT :[NeonServ %s.%d] disconnect requested.\n", NEONSERV_VERSION, patchlevel);
301         write_socket_force(client, quitbuf, quitlen);
302     }
303     client->flags &= ~(SOCKET_FLAG_READY | SOCKET_FLAG_RECONNECT);
304     client->flags |= SOCKET_FLAG_QUITTED;
305     return 1;
306 }
307
308 static void destroy_socket(struct ClientSocket *client, int free_socket) {
309     SYNCHRONIZE(synchronized);
310     if((client->flags & SOCKET_FLAG_CONNECTED)) {
311         close(client->sock);
312         bot_disconnect(client);
313     }
314     if(client->flags & SOCKET_FLAG_HAVE_SSL)
315         ssl_disconnect(client);
316     if(client->queue)
317         queue_destroy(client);
318     if(client->whoqueue_first)
319         clear_whoqueue(client);
320     if(client->handleinfo_first)
321         clear_handleinfoqueue(client);
322     client->flags &= ~(SOCKET_FLAG_CONNECTED | SOCKET_FLAG_READY | SOCKET_FLAG_HAVE_SSL);
323     if(free_socket) {
324         struct ClientSocket *sock, *last_sock = NULL;
325         for (sock = sockets->data; sock; sock = sock->next) {
326             if(sock == client) {
327                 if(last_sock)
328                     last_sock->next = sock->next;
329                 else
330                     sockets->data = sock->next;
331                 sockets->count--;
332                 break;
333             } else
334                 last_sock = sock;
335         }
336         free(client->host);
337         if(client->bind)
338             free(client->bind);
339         if(client->pass)
340             free(client->pass);
341         free(client);
342     } else if(client->flags & SOCKET_FLAG_FAST_JUMP) {
343         client->flags &= ~SOCKET_FLAG_FAST_JUMP;
344         connect_socket(client);
345     }
346     DESYNCHRONIZE(synchronized);
347 }
348
349 int write_socket_force(struct ClientSocket *client, char* msg, int len) {
350     SYNCHRONIZE(synchronized);
351     printf("[send %d] %s", len, msg);
352     if(!(client->flags & SOCKET_FLAG_HAVE_SSL) || ssl_write(client, msg, len) == -2) {
353         #ifdef WIN32
354         send(client->sock, msg, len, 0);
355         #else
356         write(client->sock, msg, len);
357         #endif
358     }
359     client->traffic_out += len;
360     DESYNCHRONIZE(synchronized);
361     return 1;
362 }
363
364 int write_socket(struct ClientSocket *client, char* msg, int len) {
365     if(!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return 0;
366     if(client->flags & SOCKET_FLAG_USE_QUEUE)
367         return queue_add(client, msg, len);
368     else
369         return write_socket_force(client, msg, len);
370 }
371
372 void socket_loop(int timeout_seconds) {
373     if(sockets == NULL) return;
374     int is_synchronized = 1;
375     SYNCHRONIZE(synchronized_recv);
376     fd_set fds;
377     struct timeval timeout;
378     struct ClientSocket *sock, *next;
379     int ret = 0, bytes, i;
380     
381     FD_ZERO(&fds);
382     for (sock = sockets->data; sock; sock = sock->next) {
383         if(!(sock->flags & SOCKET_FLAG_CONNECTED)) continue; //skip disconnected sockets
384         FD_SET(sock->sock, &fds);
385         if(sock->sock > ret)
386             ret = sock->sock;
387     }
388     timeout.tv_sec = timeout_seconds;
389     timeout.tv_usec = 0;
390     ret = select(ret + 1, &fds, NULL, NULL, &timeout);
391     if(ret == 0) {
392         DESYNCHRONIZE(synchronized_recv);
393         return;
394     }
395     for (sock = sockets->data; sock; sock = next) {
396         next = sock->next;
397         if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_QUITTED)) == SOCKET_FLAG_CONNECTED && FD_ISSET(sock->sock, &fds)) {
398             if(sock->bufferpos != 0) {
399                 if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, buffer, sizeof(buffer))) == -2) {
400                     #ifdef WIN32
401                     bytes = recv(sock->sock, buffer, sizeof(buffer), 0);
402                     #else
403                     bytes = read(sock->sock, buffer, sizeof(buffer));
404                     #endif
405                 }
406                 if(bytes > 0) {
407                     for(i = 0; i < bytes; i++) {
408                         if(sock->bufferpos + i == BUF_SIZ*2) break; //buffer overflow
409                         sock->buffer[sock->bufferpos + i] = buffer[i];
410                     }
411                     sock->bufferpos += i;
412                 }
413             } else {
414                 if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, sock->buffer, sizeof(sock->buffer))) == -2) {
415                     #ifdef WIN32
416                     bytes = recv(sock->sock, sock->buffer, sizeof(sock->buffer), 0);
417                     #else
418                     bytes = read(sock->sock, sock->buffer, sizeof(sock->buffer));
419                     #endif
420                 }
421                 if(bytes > 0)
422                     sock->bufferpos = bytes;
423             }
424             if(bytes <= 0) {
425                 //error
426                 sock->flags |= SOCKET_FLAG_QUITTED;
427             } else {
428                 sock->traffic_in += bytes;
429                 #ifdef HAVE_THREADS
430                 char linesbuf[BUF_SIZ*2];
431                 strcpy(linesbuf, sock->buffer);
432                 int used = 0;
433                 for(i = 0; i < sock->bufferpos; i++) {
434                     if(sock->buffer[i] == '\n') {
435                         used = i+1;
436                     }
437                 }
438                 if(used == sock->bufferpos + 1) {
439                     //used all bytes so just reset the bufferpos
440                     sock->bufferpos = 0;
441                 } else {
442                     for(i = 0; i < sock->bufferpos - used; i++) {
443                         sock->buffer[i] = sock->buffer[i+used];
444                     }
445                     sock->bufferpos -= used;
446                 }
447                 is_synchronized = 0;
448                 unsigned long tid = syscall(SYS_gettid);
449                 whohandler_start_of_recv(sock, tid);
450                 DESYNCHRONIZE(synchronized_recv);
451                 parse_lines(sock, linesbuf, used);
452                 whohandler_end_of_recv(sock, tid); //WHOHandler hack (unlock WHOQueue mutexes)
453                 #else
454                 int used = parse_lines(sock, sock->buffer, sock->bufferpos);
455                 if(used == sock->bufferpos + 1) {
456                     //used all bytes so just reset the bufferpos
457                     sock->bufferpos = 0;
458                 } else {
459                     for(i = 0; i < sock->bufferpos - used; i++) {
460                         sock->buffer[i] = sock->buffer[i+used];
461                     }
462                     sock->bufferpos -= used;
463                 }
464                 is_synchronized = 0;
465                 DESYNCHRONIZE(synchronized_recv);
466                 #endif
467                 #ifdef HAVE_THREADS
468                 FD_ZERO(&fds); //zero out all other pending sockets here (we have other threads receiving from them)
469                 #endif
470             }
471         } else if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT)) == SOCKET_FLAG_RECONNECT) {
472             if(time(0) - sock->connection_time >= SOCKET_RECONNECT_TIME) {
473                 connect_socket(sock);
474             }
475         }
476         if((sock->flags & SOCKET_FLAG_QUITTED)) {
477             sock->flags &= ~SOCKET_FLAG_QUITTED;
478             destroy_socket(sock, (sock->flags & SOCKET_FLAG_DEAD));
479         }
480     }
481     if(is_synchronized) {
482         DESYNCHRONIZE(synchronized_recv);
483     }
484 }
485
486 void
487 putsock(struct ClientSocket *client, const char *text, ...)
488 {
489     va_list arg_list;
490     char sendBuf[MAXLEN];
491     int pos;
492     if (!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return;
493     sendBuf[0] = '\0';
494     va_start(arg_list, text);
495     pos = vsnprintf(sendBuf, MAXLEN - 2, text, arg_list);
496     va_end(arg_list);
497     if (pos < 0 || pos > (MAXLEN - 2)) pos = MAXLEN - 2;
498     sendBuf[pos] = '\n';
499     sendBuf[pos+1] = '\0';
500     write_socket(client, sendBuf, pos+1);
501 }
502
503 struct ClientSocket* getBots(int flags, struct ClientSocket* last_bot) {
504     struct ClientSocket *sock = (last_bot ? last_bot->next : sockets->data);
505     if(sock == NULL) return NULL;
506     for (; sock; sock = sock->next) {
507         if(!flags || (sock->flags & flags) == flags)
508             return sock;
509     }
510     return NULL;
511 }
512
513 void free_sockets() {
514     if(!sockets) return;
515     struct ClientSocket *client, *next;
516     for (client = sockets->data; client; client = next) {
517         next = client->next;
518         if((client->flags & SOCKET_FLAG_CONNECTED))
519             close(client->sock);
520         if(client->flags & SOCKET_FLAG_HAVE_SSL)
521             ssl_disconnect(client);
522         if(client->queue)
523             queue_destroy(client);
524         free(client->host);
525         if(client->bind)
526             free(client->bind);
527         if(client->pass)
528             free(client->pass);
529         free(client);
530     }
531     free(sockets);
532     sockets = NULL;
533 }