fixed compilation without threads and fixed some warnings
[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         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     if(ret == 0) {
449         DESYNCHRONIZE(synchronized_recv);
450         return 1;
451     }
452     for (sock = sockets->data; sock; sock = next) {
453         next = sock->next;
454         if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_QUITTED)) == SOCKET_FLAG_CONNECTED && FD_ISSET(sock->sock, &fds)) {
455             if(sock->bufferpos != 0) {
456                 if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, buffer, sizeof(buffer))) == -2) {
457                     #ifdef WIN32
458                     bytes = recv(sock->sock, buffer, sizeof(buffer), 0);
459                     #else
460                     bytes = read(sock->sock, buffer, sizeof(buffer));
461                     #endif
462                 }
463                 if(bytes > 0) {
464                     for(i = 0; i < bytes; i++) {
465                         if(sock->bufferpos + i == BUF_SIZ*2) break; //buffer overflow
466                         sock->buffer[sock->bufferpos + i] = buffer[i];
467                     }
468                     sock->bufferpos += i;
469                 }
470             } else {
471                 if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, sock->buffer, sizeof(sock->buffer))) == -2) {
472                     #ifdef WIN32
473                     bytes = recv(sock->sock, sock->buffer, sizeof(sock->buffer), 0);
474                     #else
475                     bytes = read(sock->sock, sock->buffer, sizeof(sock->buffer));
476                     #endif
477                 }
478                 if(bytes > 0)
479                     sock->bufferpos = bytes;
480             }
481             if(bytes <= 0) {
482                 //error
483                 sock->flags |= SOCKET_FLAG_QUITTED;
484             } else {
485                 sock->traffic_in += bytes;
486                 #ifdef HAVE_THREADS
487                 char linesbuf[BUF_SIZ*2];
488                 strcpy(linesbuf, sock->buffer);
489                 int used = 0;
490                 for(i = 0; i < sock->bufferpos; i++) {
491                     if(sock->buffer[i] == '\n') {
492                         used = i+1;
493                     }
494                 }
495                 if(used == sock->bufferpos + 1) {
496                     //used all bytes so just reset the bufferpos
497                     sock->bufferpos = 0;
498                 } else {
499                     for(i = 0; i < sock->bufferpos - used; i++) {
500                         sock->buffer[i] = sock->buffer[i+used];
501                     }
502                     sock->bufferpos -= used;
503                 }
504                 is_synchronized = 0;
505                 unsigned int tid = (unsigned int) pthread_self_tid();
506                 clientsocket_start_of_recv(tid);
507                 DESYNCHRONIZE(synchronized_recv);
508                 parse_lines(sock, linesbuf, used);
509                 clientsocket_end_of_recv(tid);
510                 #else
511                 int used = parse_lines(sock, sock->buffer, sock->bufferpos);
512                 if(used == sock->bufferpos + 1) {
513                     //used all bytes so just reset the bufferpos
514                     sock->bufferpos = 0;
515                 } else {
516                     for(i = 0; i < sock->bufferpos - used; i++) {
517                         sock->buffer[i] = sock->buffer[i+used];
518                     }
519                     sock->bufferpos -= used;
520                 }
521                 is_synchronized = 0;
522                 DESYNCHRONIZE(synchronized_recv);
523                 #endif
524                 #ifdef HAVE_THREADS
525                 FD_ZERO(&fds); //zero out all other pending sockets here (we have other threads receiving from them)
526                 #endif
527             }
528         } else if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT)) == SOCKET_FLAG_RECONNECT) {
529             if(time(0) - sock->connection_time >= SOCKET_RECONNECT_TIME) {
530                 connect_socket(sock);
531             }
532         }
533         if((sock->flags & SOCKET_FLAG_QUITTED)) {
534             sock->flags &= ~SOCKET_FLAG_QUITTED;
535             destroy_socket(sock, (sock->flags & SOCKET_FLAG_DEAD));
536         }
537     }
538     if(is_synchronized) {
539         DESYNCHRONIZE(synchronized_recv);
540     }
541     return (ret + 1);
542 }
543
544 void
545 putsock(struct ClientSocket *client, const char *text, ...)
546 {
547     va_list arg_list;
548     char sendBuf[MAXLEN];
549     int pos;
550     if (!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return;
551     sendBuf[0] = '\0';
552     va_start(arg_list, text);
553     pos = vsnprintf(sendBuf, MAXLEN - 2, text, arg_list);
554     va_end(arg_list);
555     if (pos < 0 || pos > (MAXLEN - 2)) pos = MAXLEN - 2;
556     sendBuf[pos] = '\n';
557     sendBuf[pos+1] = '\0';
558     write_socket(client, sendBuf, pos+1);
559 }
560
561 struct ClientSocket* getBots(int flags, struct ClientSocket* last_bot) {
562     struct ClientSocket *sock = (last_bot ? last_bot->next : sockets->data);
563     if(sock == NULL) return NULL;
564     for (; sock; sock = sock->next) {
565         if(!flags || (sock->flags & flags) == flags)
566             return sock;
567     }
568     return NULL;
569 }
570
571 void free_sockets() {
572     if(!sockets) return;
573     struct ClientSocket *client, *next;
574     for (client = sockets->data; client; client = next) {
575         next = client->next;
576         if((client->flags & SOCKET_FLAG_CONNECTED))
577             close(client->sock);
578         if(client->flags & SOCKET_FLAG_HAVE_SSL)
579             ssl_disconnect(client);
580         if(client->queue)
581             queue_destroy(client);
582         free(client->host);
583         if(client->bind)
584             free(client->bind);
585         if(client->pass)
586             free(client->pass);
587         if(client->network_name)
588             free(client->network_name);
589         free(client);
590     }
591     free(sockets);
592     sockets = NULL;
593 }