added stats module for neonserv.krypton-bouncer.de stats
[NeonServV5.git] / src / ClientSocket.c
index 30c2efb4ec7e2d9c7cf69280fc47719720a36884..d1f80ff8773358a09a9c557b216afbea9c8490c8 100644 (file)
@@ -1,18 +1,54 @@
+/* ClientSocket.c - NeonServ v5.4
+ * Copyright (C) 2011-2012  Philipp Kreil (pk910)
+ * 
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ * 
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ * 
+ * You should have received a copy of the GNU General Public License 
+ * along with this program. If not, see <http://www.gnu.org/licenses/>. 
+ */
 
 #include "ClientSocket.h"
 #include "IRCParser.h"
 #include "UserNode.h"
+#include "IRCQueue.h"
+#include "WHOHandler.h"
+#include "HandleInfoHandler.h"
+#include "ssl.h"
+#include "ConfigParser.h"
+#include "version.h"
 
 struct socket_list {
     struct ClientSocket *data;
     unsigned count;
 };
 
+#ifdef HAVE_THREADS
+static pthread_mutex_t synchronized;
+static pthread_mutex_t synchronized_recv;
+
+struct ParseOrder {
+    unsigned int tid;
+    struct ParseOrder *next;
+};
+struct ParseOrder *parse_order = NULL;
+#endif
+
 //the magic list :P
 static struct socket_list *sockets = NULL;
 static char buffer[BUF_SIZ];
 
-static void init_sockets() {
+void init_sockets() {
+    THREAD_MUTEX_INIT(synchronized);
+    THREAD_MUTEX_INIT(synchronized_recv);
+    
     sockets = malloc(sizeof(*sockets));
     if (!sockets)
     {
@@ -23,8 +59,7 @@ static void init_sockets() {
     sockets->count = 0;
 }
 
-struct ClientSocket* create_socket(char *host, int port, char *pass, struct UserNode *user) {
-    if(sockets == NULL) init_sockets();
+struct ClientSocket* create_socket(char *host, int port, char *bindto, char *pass, char *nick, char *ident, char *realname) {
     struct ClientSocket *client = malloc(sizeof(*client));
     if (!client)
     {
@@ -33,9 +68,13 @@ struct ClientSocket* create_socket(char *host, int port, char *pass, struct User
     }
     client->host = strdup(host);
     client->port = port;
-    printf("Connect: %s:%d\n", client->host, client->port);
+    client->bind = (bindto ? strdup(bindto) : NULL);
     client->pass = (pass == NULL ? NULL : strdup(pass));
-    client->user = user;
+    client->nick = strdup(nick);
+    client->ident = strdup(ident);
+    client->realname = strdup(realname);
+    client->user = NULL;
+    client->network_name = NULL;
     client->flags = 0;
     client->bufferpos = 0;
     client->traffic_in = 0;
@@ -43,78 +82,167 @@ struct ClientSocket* create_socket(char *host, int port, char *pass, struct User
     client->connection_time = 0;
        client->botid = 0;
     client->clientid = 0;
+    client->queue = NULL;
+    client->whoqueue_first = NULL;
+    client->whoqueue_last = NULL;
+    client->handleinfo_first = NULL;
+    client->handleinfo_last = NULL;
+    SYNCHRONIZE(synchronized);
     client->next = sockets->data;
     sockets->data = client;
+    DESYNCHRONIZE(synchronized);
     return client;
 }
 
-#ifdef WIN32
+static int _connect_socket(struct ClientSocket *client);
 
 int connect_socket(struct ClientSocket *client) {
+    SYNCHRONIZE(synchronized);
+    int ret = _connect_socket(client);
+    DESYNCHRONIZE(synchronized);
+    return ret;
+}
+
+#ifndef WIN32
+static int _connect_socket(struct ClientSocket *client) {
     if((client->flags & SOCKET_FLAG_CONNECTED)) return 1;
-    struct hostent *host;
-    struct sockaddr_in addr;
     int sock;
-    addr.sin_addr.s_addr = inet_addr(client->host);
-    if (addr.sin_addr.s_addr == INADDR_NONE) {
-        host = gethostbyname(client->host);
-        if(!host) {
-            return SOCKET_ERROR;
-        }
-        memcpy(&(addr.sin_addr), host->h_addr_list[0], 4);
-    }
-    sock = socket(PF_INET, SOCK_STREAM, 0);
-    if (sock == -1)
-    {
-        perror("socket() failed");
+    
+    struct addrinfo hints, *res;
+    struct sockaddr_in *ip4 = NULL;
+    struct sockaddr_in6 *ip6 = NULL;
+    memset (&hints, 0, sizeof (hints));
+    hints.ai_family = PF_UNSPEC;
+    hints.ai_socktype = SOCK_STREAM;
+    hints.ai_flags |= AI_CANONNAME;
+    if (getaddrinfo (client->host, NULL, &hints, &res)) {
         return 0;
     }
-
-    addr.sin_port = htons(client->port);
-    addr.sin_family = AF_INET;
-
-    if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1)
-    {
-        perror("connect() failed");
+    while (res) {
+        switch (res->ai_family) {
+        case AF_INET:
+            ip4 = (struct sockaddr_in *) res->ai_addr;
+            break;
+        case AF_INET6:
+            ip6 = (struct sockaddr_in6 *) res->ai_addr;
+            break;
+        }
+        res = res->ai_next;
+    }
+    
+    if(ip6) {
+        sock = socket(AF_INET6, SOCK_STREAM, 0);
+        if(sock == -1) {
+            perror("socket() failed");
+            return 0;
+        }
+        
+        ip6->sin6_family = AF_INET6;
+        ip6->sin6_port = htons(client->port);
+        
+        struct sockaddr_in6 *ip6vhost = NULL;
+        if (client->bind && !getaddrinfo(client->bind, NULL, &hints, &res)) {
+            while (res) {
+                switch (res->ai_family) {
+                case AF_INET6:
+                    ip6vhost = (struct sockaddr_in6 *) res->ai_addr;
+                    break;
+                }
+                res = res->ai_next;
+            }
+        }
+        if(ip6vhost) {
+            ip6vhost->sin6_family = AF_INET6;
+            ip6vhost->sin6_port = htons(0);
+            bind(sock, (struct sockaddr*)ip6vhost, sizeof(*ip6vhost));
+        }
+        
+        if (connect(sock, (struct sockaddr*)ip6, sizeof(*ip6)) == -1) {
+            perror("connect() failed");
+            return 0;
+        }
+        
+    } else if(ip4) {
+        sock = socket(AF_INET, SOCK_STREAM, 0);
+        if(sock == -1) {
+            perror("socket() failed");
+            return 0;
+        }
+        
+        ip4->sin_family = AF_INET;
+        ip4->sin_port = htons(client->port);
+        
+        struct sockaddr_in *ip4vhost = NULL;
+        if (client->bind && !getaddrinfo(client->bind, NULL, &hints, &res)) {
+            while (res) {
+                switch (res->ai_family) {
+                case AF_INET:
+                    ip4vhost = (struct sockaddr_in *) res->ai_addr;
+                    break;
+                }
+                res = res->ai_next;
+            }
+        }
+        if(ip4vhost) {
+            ip4vhost->sin_family = AF_INET;
+            ip4vhost->sin_port = htons(0);
+            bind(sock, (struct sockaddr*)ip4vhost, sizeof(*ip4vhost));
+        }
+        
+        if (connect(sock, (struct sockaddr*)ip4, sizeof(*ip4)) == -1) {
+            perror("connect() failed");
+            return 0;
+        }
+        
+    } else
         return 0;
+    
+    if(get_int_field("Sockets.NoDelay")) {
+        int flag = 1;
+        if(setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int)) == -1) {
+            perror("setsockopt() failed");
+            return 0;
+        }
     }
-
+    
     client->sock = sock;
-    client->flags |= SOCKET_FLAG_CONNECTED;
+    client->flags |= SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT;
     client->connection_time = time(0);
-
+    
+    if(client->flags & SOCKET_FLAG_SSL) {
+        ssl_connect(client);
+        client->flags |= SOCKET_FLAG_HAVE_SSL;
+    } else
+        client->flags &= ~SOCKET_FLAG_HAVE_SSL;
+    
     //send the IRC Headers
     char sendBuf[512];
     int len;
-
+    
     if(client->pass && strcmp(client->pass, "")) {
         len = sprintf(sendBuf, "PASS :%s\n", client->pass);
         write_socket(client, sendBuf, len);
     }
-    len = sprintf(sendBuf, "USER %s 0 0 :%s\n", client->user->ident, client->user->realname);
+    len = sprintf(sendBuf, "USER %s 0 0 :%s\n", client->ident, client->realname);
     write_socket(client, sendBuf, len);
-    len = sprintf(sendBuf, "NICK %s\n", client->user->nick);
+    len = sprintf(sendBuf, "NICK %s\n", client->nick);
     write_socket(client, sendBuf, len);
-
+    
     return 1;
 }
-
 #else
-
-int connect_socket(struct ClientSocket *client) {
+static int _connect_socket(struct ClientSocket *client) {
     if((client->flags & SOCKET_FLAG_CONNECTED)) return 1;
     struct hostent *host;
     struct sockaddr_in addr;
     int sock;
-    if (!inet_aton(client->host, &addr.sin_addr))
-    {
+    addr.sin_addr.s_addr = inet_addr(client->host);
+    if (addr.sin_addr.s_addr == INADDR_NONE) {
         host = gethostbyname(client->host);
-        if (!host)
-        {
-            perror("gethostbyname() failed");
-            return 0;
+        if(!host) {
+            return SOCKET_ERROR;
         }
-        addr.sin_addr = *(struct in_addr*)host->h_addr;
+        memcpy(&(addr.sin_addr), host->h_addr_list[0], 4);
     }
     sock = socket(PF_INET, SOCK_STREAM, 0);
     if (sock == -1)
@@ -133,65 +261,177 @@ int connect_socket(struct ClientSocket *client) {
     }
 
     client->sock = sock;
-    client->flags |= SOCKET_FLAG_CONNECTED;
+    client->flags |= SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT;
     client->connection_time = time(0);
 
+
+    if(client->flags & SOCKET_FLAG_SSL) {
+        ssl_connect(client);
+        client->flags |= SOCKET_FLAG_HAVE_SSL;
+    } else
+        client->flags &= ~SOCKET_FLAG_HAVE_SSL;
+
     //send the IRC Headers
     char sendBuf[512];
     int len;
 
-    if(client->pass) {
+    if(client->pass && strcmp(client->pass, "")) {
         len = sprintf(sendBuf, "PASS :%s\n", client->pass);
         write_socket(client, sendBuf, len);
     }
-    len = sprintf(sendBuf, "USER %s 0 0 :%s\n", client->user->ident, client->user->realname);
+    len = sprintf(sendBuf, "USER %s 0 0 :%s\n", client->ident, client->realname);
     write_socket(client, sendBuf, len);
-    len = sprintf(sendBuf, "NICK %s\n", client->user->nick);
+    len = sprintf(sendBuf, "NICK %s\n", client->nick);
     write_socket(client, sendBuf, len);
 
     return 1;
 }
-
 #endif
 
 int close_socket(struct ClientSocket *client) {
     if(client == NULL) return 0;
-    if((client->flags & SOCKET_FLAG_CONNECTED))
-        close(client->sock);
-    struct ClientSocket *sock, *last_sock = NULL;
-    for (sock = sockets->data; sock; sock = sock->next) {
-        if(sock == client) {
-            if(last_sock)
-                last_sock->next = sock->next;
-            else
-                sockets->data = sock->next;
-            sockets->count--;
-        } else
-            last_sock = sock;
+    if((client->flags & SOCKET_FLAG_CONNECTED)) {
+        char quitbuf[MAXLEN];
+        int quitlen = sprintf(quitbuf, "QUIT :[NeonServ %s.%d] disconnect requested.\n", NEONSERV_VERSION, patchlevel);
+        write_socket_force(client, quitbuf, quitlen);
     }
-    free(client->host);
-    free(client->pass);
-    free(client);
+    client->flags &= ~(SOCKET_FLAG_READY | SOCKET_FLAG_RECONNECT);
+    client->flags |= SOCKET_FLAG_QUITTED | SOCKET_FLAG_DEAD;
     return 1;
 }
 
-int write_socket(struct ClientSocket *client, char* msg, int len) {
-    if(!(client->flags & SOCKET_FLAG_CONNECTED)) return 0;
-    printf("[send %d] %s", len, msg);
-    #ifdef WIN32
-    send(client->sock, msg, len, 0);
+int disconnect_socket(struct ClientSocket *client) {
+    if(client == NULL) return 0;
+    if((client->flags & SOCKET_FLAG_CONNECTED)) {
+        char quitbuf[MAXLEN];
+        int quitlen = sprintf(quitbuf, "QUIT :[NeonServ %s.%d] disconnect requested.\n", NEONSERV_VERSION, patchlevel);
+        write_socket_force(client, quitbuf, quitlen);
+    }
+    client->flags &= ~(SOCKET_FLAG_READY | SOCKET_FLAG_RECONNECT);
+    client->flags |= SOCKET_FLAG_QUITTED;
+    return 1;
+}
+
+static void destroy_socket(struct ClientSocket *client, int free_socket) {
+    SYNCHRONIZE(synchronized);
+    if((client->flags & SOCKET_FLAG_CONNECTED)) {
+        close(client->sock);
+        bot_disconnect(client);
+    }
+    if(client->flags & SOCKET_FLAG_HAVE_SSL)
+        ssl_disconnect(client);
+    if(client->queue)
+        queue_destroy(client);
+    if(client->whoqueue_first)
+        clear_whoqueue(client);
+    if(client->handleinfo_first)
+        clear_handleinfoqueue(client);
+    client->flags &= ~(SOCKET_FLAG_CONNECTED | SOCKET_FLAG_READY | SOCKET_FLAG_HAVE_SSL);
+    if(free_socket) {
+        struct ClientSocket *sock, *last_sock = NULL;
+        for (sock = sockets->data; sock; sock = sock->next) {
+            if(sock == client) {
+                if(last_sock)
+                    last_sock->next = sock->next;
+                else
+                    sockets->data = sock->next;
+                sockets->count--;
+                break;
+            } else
+                last_sock = sock;
+        }
+        free(client->host);
+        if(client->bind)
+            free(client->bind);
+        if(client->pass)
+            free(client->pass);
+        if(client->network_name)
+            free(client->network_name);
+        free(client);
+    } else if(client->flags & SOCKET_FLAG_FAST_JUMP) {
+        client->flags &= ~SOCKET_FLAG_FAST_JUMP;
+        connect_socket(client);
+    }
+    DESYNCHRONIZE(synchronized);
+}
+
+int write_socket_force(struct ClientSocket *client, char* msg, int len) {
+    SYNCHRONIZE(synchronized);
+    #ifdef HAVE_THREADS
+    putlog(LOGLEVEL_RAW, "[%d send %d] %s", getCurrentThreadID(), len, msg);
     #else
-    write(client->sock, msg, len);
+    putlog(LOGLEVEL_RAW, "[send %d] %s", len, msg);
     #endif
+    if(!(client->flags & SOCKET_FLAG_HAVE_SSL) || ssl_write(client, msg, len) == -2) {
+        #ifdef WIN32
+        send(client->sock, msg, len, 0);
+        #else
+        write(client->sock, msg, len);
+        #endif
+    }
     client->traffic_out += len;
+    DESYNCHRONIZE(synchronized);
     return 1;
 }
 
-void socket_loop(int timeout_seconds) {
-    if(sockets == NULL) return;
+int write_socket(struct ClientSocket *client, char* msg, int len) {
+    if(!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return 0;
+    if(client->flags & SOCKET_FLAG_USE_QUEUE)
+        return queue_add(client, msg, len);
+    else
+        return write_socket_force(client, msg, len);
+}
+
+#if HAVE_THREADS
+static void clientsocket_start_of_recv(unsigned int tid) {
+    SYNCHRONIZE(whohandler_sync);
+    struct ParseOrder *entry, *last;
+    for(last = parse_order; last; last = last->next) {
+        if(last->next == NULL)
+            break;
+    }
+    entry = malloc(sizeof(*entry));
+    entry->tid = tid;
+    entry->next = NULL;
+    if(last)
+        last->next = entry;
+    else
+        parse_order = entry;
+    DESYNCHRONIZE(whohandler_sync);
+}
+
+static void clientsocket_end_of_recv(unsigned int tid) {
+    SYNCHRONIZE(whohandler_sync);
+    struct ParseOrder *entry, *last = NULL;
+    for(entry = parse_order; entry; entry = entry->next) {
+        if(entry->tid == tid) {
+            if(last)
+                last->next = entry->next;
+            else
+                parse_order = entry->next;
+            free(entry);
+            break;
+        } else
+            last = entry;
+    }
+    DESYNCHRONIZE(whohandler_sync);
+}
+
+int clientsocket_parseorder_top(unsigned int tid) {
+    if(parse_order && parse_order->tid == tid)
+        return 1;
+    else
+        return 0;
+}
+#endif
+
+int socket_loop(int timeout_seconds) {
+    if(sockets == NULL) return 0;
+    int is_synchronized = 1;
+    SYNCHRONIZE(synchronized_recv);
     fd_set fds;
     struct timeval timeout;
-    struct ClientSocket *sock;
+    struct ClientSocket *sock, *next;
     int ret = 0, bytes, i;
     
     FD_ZERO(&fds);
@@ -204,15 +444,21 @@ void socket_loop(int timeout_seconds) {
     timeout.tv_sec = timeout_seconds;
     timeout.tv_usec = 0;
     ret = select(ret + 1, &fds, NULL, NULL, &timeout);
-    if(ret == 0) return;
-    for (sock = sockets->data; sock; sock = sock->next) {
-        if((sock->flags & SOCKET_FLAG_CONNECTED) && FD_ISSET(sock->sock, &fds)) {
+    if(ret == 0) {
+        DESYNCHRONIZE(synchronized_recv);
+        return 1;
+    }
+    for (sock = sockets->data; sock; sock = next) {
+        next = sock->next;
+        if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_QUITTED)) == SOCKET_FLAG_CONNECTED && FD_ISSET(sock->sock, &fds)) {
             if(sock->bufferpos != 0) {
-                #ifdef WIN32
-                bytes = recv(sock->sock, buffer, sizeof(buffer), 0);
-                #else
-                bytes = read(sock->sock, buffer, sizeof(buffer));
-                #endif
+                if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, buffer, sizeof(buffer))) == -2) {
+                    #ifdef WIN32
+                    bytes = recv(sock->sock, buffer, sizeof(buffer), 0);
+                    #else
+                    bytes = read(sock->sock, buffer, sizeof(buffer));
+                    #endif
+                }
                 if(bytes > 0) {
                     for(i = 0; i < bytes; i++) {
                         if(sock->bufferpos + i == BUF_SIZ*2) break; //buffer overflow
@@ -221,20 +467,46 @@ void socket_loop(int timeout_seconds) {
                     sock->bufferpos += i;
                 }
             } else {
-                #ifdef WIN32
-                bytes = recv(sock->sock, sock->buffer, sizeof(sock->buffer), 0);
-                #else
-                bytes = read(sock->sock, sock->buffer, sizeof(sock->buffer));
-                #endif
+                if(!(sock->flags & SOCKET_FLAG_HAVE_SSL) || (bytes = ssl_read(sock, sock->buffer, sizeof(sock->buffer))) == -2) {
+                    #ifdef WIN32
+                    bytes = recv(sock->sock, sock->buffer, sizeof(sock->buffer), 0);
+                    #else
+                    bytes = read(sock->sock, sock->buffer, sizeof(sock->buffer));
+                    #endif
+                }
                 if(bytes > 0)
                     sock->bufferpos = bytes;
             }
             if(bytes <= 0) {
                 //error
-                sock->flags &= ~(SOCKET_FLAG_CONNECTED | SOCKET_FLAG_READY);
-                bot_disconnect(sock);
+                sock->flags |= SOCKET_FLAG_QUITTED;
             } else {
                 sock->traffic_in += bytes;
+                #ifdef HAVE_THREADS
+                char linesbuf[BUF_SIZ*2];
+                strcpy(linesbuf, sock->buffer);
+                int used = 0;
+                for(i = 0; i < sock->bufferpos; i++) {
+                    if(sock->buffer[i] == '\n') {
+                        used = i+1;
+                    }
+                }
+                if(used == sock->bufferpos + 1) {
+                    //used all bytes so just reset the bufferpos
+                    sock->bufferpos = 0;
+                } else {
+                    for(i = 0; i < sock->bufferpos - used; i++) {
+                        sock->buffer[i] = sock->buffer[i+used];
+                    }
+                    sock->bufferpos -= used;
+                }
+                is_synchronized = 0;
+                unsigned int tid = (unsigned int) pthread_self_tid();
+                clientsocket_start_of_recv(tid);
+                DESYNCHRONIZE(synchronized_recv);
+                parse_lines(sock, linesbuf, used);
+                clientsocket_end_of_recv(tid);
+                #else
                 int used = parse_lines(sock, sock->buffer, sock->bufferpos);
                 if(used == sock->bufferpos + 1) {
                     //used all bytes so just reset the bufferpos
@@ -245,9 +517,27 @@ void socket_loop(int timeout_seconds) {
                     }
                     sock->bufferpos -= used;
                 }
+                is_synchronized = 0;
+                DESYNCHRONIZE(synchronized_recv);
+                #endif
+                #ifdef HAVE_THREADS
+                FD_ZERO(&fds); //zero out all other pending sockets here (we have other threads receiving from them)
+                #endif
+            }
+        } else if((sock->flags & (SOCKET_FLAG_CONNECTED | SOCKET_FLAG_RECONNECT)) == SOCKET_FLAG_RECONNECT) {
+            if(time(0) - sock->connection_time >= SOCKET_RECONNECT_TIME) {
+                connect_socket(sock);
             }
         }
+        if((sock->flags & SOCKET_FLAG_QUITTED)) {
+            sock->flags &= ~SOCKET_FLAG_QUITTED;
+            destroy_socket(sock, (sock->flags & SOCKET_FLAG_DEAD));
+        }
+    }
+    if(is_synchronized) {
+        DESYNCHRONIZE(synchronized_recv);
     }
+    return (ret + 1);
 }
 
 void
@@ -256,7 +546,7 @@ putsock(struct ClientSocket *client, const char *text, ...)
     va_list arg_list;
     char sendBuf[MAXLEN];
     int pos;
-    if (!(client->flags & SOCKET_FLAG_CONNECTED)) return;
+    if (!(client && (client->flags & SOCKET_FLAG_CONNECTED))) return;
     sendBuf[0] = '\0';
     va_start(arg_list, text);
     pos = vsnprintf(sendBuf, MAXLEN - 2, text, arg_list);
@@ -284,8 +574,17 @@ void free_sockets() {
         next = client->next;
         if((client->flags & SOCKET_FLAG_CONNECTED))
             close(client->sock);
+        if(client->flags & SOCKET_FLAG_HAVE_SSL)
+            ssl_disconnect(client);
+        if(client->queue)
+            queue_destroy(client);
         free(client->host);
-        free(client->pass);
+        if(client->bind)
+            free(client->bind);
+        if(client->pass)
+            free(client->pass);
+        if(client->network_name)
+            free(client->network_name);
         free(client);
     }
     free(sockets);