added "first time" configuration (set up first bot and admin user)
[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
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     printf("[send %d] %s", len, msg);
358     if(!(client->flags & SOCKET_FLAG_HAVE_SSL) || ssl_write(client, msg, len) == -2) {
359         #ifdef WIN32
360         send(client->sock, msg, len, 0);
361         #else
362         write(client->sock, msg, len);
363         #endif
364     }
365     client->traffic_out += len;
366     DESYNCHRONIZE(synchronized);
367     return 1;
368 }
369
370 int write_socket(struct ClientSocket *client, char* msg, int len) {
371     if(!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return 0;
372     if(client->flags & SOCKET_FLAG_USE_QUEUE)
373         return queue_add(client, msg, len);
374     else
375         return write_socket_force(client, msg, len);
376 }
377
378 #if HAVE_THREADS
379 static void clientsocket_start_of_recv(unsigned int tid) {
380     SYNCHRONIZE(whohandler_sync);
381     struct ParseOrder *entry, *last;
382     for(last = parse_order; last; last = last->next) {
383         if(last->next == NULL)
384             break;
385     }
386     entry = malloc(sizeof(*entry));
387     entry->tid = tid;
388     entry->next = NULL;
389     if(last)
390         last->next = entry;
391     else
392         parse_order = entry;
393     DESYNCHRONIZE(whohandler_sync);
394 }
395
396 static void clientsocket_end_of_recv(unsigned int tid) {
397     SYNCHRONIZE(whohandler_sync);
398     struct ParseOrder *entry, *last = NULL;
399     for(entry = parse_order; entry; entry = entry->next) {
400         if(entry->tid == tid) {
401             if(last)
402                 last->next = entry->next;
403             else
404                 parse_order = entry->next;
405             free(entry);
406             break;
407         } else
408             last = entry;
409     }
410     DESYNCHRONIZE(whohandler_sync);
411 }
412
413 int clientsocket_parseorder_top(unsigned int tid) {
414     if(parse_order && parse_order->tid == tid)
415         return 1;
416     else
417         return 0;
418 }
419 #endif
420
421 int socket_loop(int timeout_seconds) {
422     if(sockets == NULL) return 0;
423     int is_synchronized = 1;
424     SYNCHRONIZE(synchronized_recv);
425     fd_set fds;
426     struct timeval timeout;
427     struct ClientSocket *sock, *next;
428     int ret = 0, bytes, i;
429     
430     FD_ZERO(&fds);
431     for (sock = sockets->data; sock; sock = sock->next) {
432         if(!(sock->flags & SOCKET_FLAG_CONNECTED)) continue; //skip disconnected sockets
433         FD_SET(sock->sock, &fds);
434         if(sock->sock > ret)
435             ret = sock->sock;
436     }
437     timeout.tv_sec = timeout_seconds;
438     timeout.tv_usec = 0;
439     ret = select(ret + 1, &fds, NULL, NULL, &timeout);
440     if(ret == 0) {
441         DESYNCHRONIZE(synchronized_recv);
442         return 1;
443     }
444     for (sock = sockets->data; sock; sock = next) {
445         next = sock->next;
446         if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_QUITTED)) == SOCKET_FLAG_CONNECTED && FD_ISSET(sock->sock, &fds)) {
447             if(sock->bufferpos != 0) {
448                 if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, buffer, sizeof(buffer))) == -2) {
449                     #ifdef WIN32
450                     bytes = recv(sock->sock, buffer, sizeof(buffer), 0);
451                     #else
452                     bytes = read(sock->sock, buffer, sizeof(buffer));
453                     #endif
454                 }
455                 if(bytes > 0) {
456                     for(i = 0; i < bytes; i++) {
457                         if(sock->bufferpos + i == BUF_SIZ*2) break; //buffer overflow
458                         sock->buffer[sock->bufferpos + i] = buffer[i];
459                     }
460                     sock->bufferpos += i;
461                 }
462             } else {
463                 if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, sock->buffer, sizeof(sock->buffer))) == -2) {
464                     #ifdef WIN32
465                     bytes = recv(sock->sock, sock->buffer, sizeof(sock->buffer), 0);
466                     #else
467                     bytes = read(sock->sock, sock->buffer, sizeof(sock->buffer));
468                     #endif
469                 }
470                 if(bytes > 0)
471                     sock->bufferpos = bytes;
472             }
473             if(bytes <= 0) {
474                 //error
475                 sock->flags |= SOCKET_FLAG_QUITTED;
476             } else {
477                 sock->traffic_in += bytes;
478                 #ifdef HAVE_THREADS
479                 char linesbuf[BUF_SIZ*2];
480                 strcpy(linesbuf, sock->buffer);
481                 int used = 0;
482                 for(i = 0; i < sock->bufferpos; i++) {
483                     if(sock->buffer[i] == '\n') {
484                         used = i+1;
485                     }
486                 }
487                 if(used == sock->bufferpos + 1) {
488                     //used all bytes so just reset the bufferpos
489                     sock->bufferpos = 0;
490                 } else {
491                     for(i = 0; i < sock->bufferpos - used; i++) {
492                         sock->buffer[i] = sock->buffer[i+used];
493                     }
494                     sock->bufferpos -= used;
495                 }
496                 is_synchronized = 0;
497                 unsigned int tid = (unsigned int) pthread_self_tid();
498                 clientsocket_start_of_recv(tid);
499                 DESYNCHRONIZE(synchronized_recv);
500                 parse_lines(sock, linesbuf, used);
501                 clientsocket_end_of_recv(tid);
502                 #else
503                 int used = parse_lines(sock, sock->buffer, sock->bufferpos);
504                 if(used == sock->bufferpos + 1) {
505                     //used all bytes so just reset the bufferpos
506                     sock->bufferpos = 0;
507                 } else {
508                     for(i = 0; i < sock->bufferpos - used; i++) {
509                         sock->buffer[i] = sock->buffer[i+used];
510                     }
511                     sock->bufferpos -= used;
512                 }
513                 is_synchronized = 0;
514                 DESYNCHRONIZE(synchronized_recv);
515                 #endif
516                 #ifdef HAVE_THREADS
517                 FD_ZERO(&fds); //zero out all other pending sockets here (we have other threads receiving from them)
518                 #endif
519             }
520         } else if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT)) == SOCKET_FLAG_RECONNECT) {
521             if(time(0) - sock->connection_time >= SOCKET_RECONNECT_TIME) {
522                 connect_socket(sock);
523             }
524         }
525         if((sock->flags & SOCKET_FLAG_QUITTED)) {
526             sock->flags &= ~SOCKET_FLAG_QUITTED;
527             destroy_socket(sock, (sock->flags & SOCKET_FLAG_DEAD));
528         }
529     }
530     if(is_synchronized) {
531         DESYNCHRONIZE(synchronized_recv);
532     }
533     return (ret + 1);
534 }
535
536 void
537 putsock(struct ClientSocket *client, const char *text, ...)
538 {
539     va_list arg_list;
540     char sendBuf[MAXLEN];
541     int pos;
542     if (!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return;
543     sendBuf[0] = '\0';
544     va_start(arg_list, text);
545     pos = vsnprintf(sendBuf, MAXLEN - 2, text, arg_list);
546     va_end(arg_list);
547     if (pos < 0 || pos > (MAXLEN - 2)) pos = MAXLEN - 2;
548     sendBuf[pos] = '\n';
549     sendBuf[pos+1] = '\0';
550     write_socket(client, sendBuf, pos+1);
551 }
552
553 struct ClientSocket* getBots(int flags, struct ClientSocket* last_bot) {
554     struct ClientSocket *sock = (last_bot ? last_bot->next : sockets->data);
555     if(sock == NULL) return NULL;
556     for (; sock; sock = sock->next) {
557         if(!flags || (sock->flags & flags) == flags)
558             return sock;
559     }
560     return NULL;
561 }
562
563 void free_sockets() {
564     if(!sockets) return;
565     struct ClientSocket *client, *next;
566     for (client = sockets->data; client; client = next) {
567         next = client->next;
568         if((client->flags & SOCKET_FLAG_CONNECTED))
569             close(client->sock);
570         if(client->flags & SOCKET_FLAG_HAVE_SSL)
571             ssl_disconnect(client);
572         if(client->queue)
573             queue_destroy(client);
574         free(client->host);
575         if(client->bind)
576             free(client->bind);
577         if(client->pass)
578             free(client->pass);
579         free(client);
580     }
581     free(sockets);
582     sockets = NULL;
583 }