fixed WIN32 compatibility
[NeonServV5.git] / src / main.c
index 6486d6cb3a3de881feff95cf39823cfc4412a8a8..fbf9ed5806f4b93d9cb0c292c1a07feb4ff32794 100644 (file)
 #include "ModeNode.h"
 #include "IRCQueue.h"
 #include "DBHelper.h"
-#include "commands.h"
 #include "ConfigParser.h"
 #include "ssl.h"
 #include "QServer.h"
 #include "version.h"
+#include "modules.h"
+#include "module_commands.h"
 
 time_t start_time;
 static int running, hard_restart;
@@ -58,7 +59,10 @@ pthread_mutex_t whohandler_sync, whohandler_mass_sync;
 static pthread_mutex_t log_sync;
 #endif
 
+static void check_firstrun();
+
 void cleanup() {
+    stop_modules();
     free_sockets();
     qserver_free();
     free_parser();
@@ -67,7 +71,6 @@ void cleanup() {
     free_bind();
     free_modcmd();
     free_whoqueue();
-    free_bots();
     free_mysql();
     free_handleinfohandler();
     free_lang();
@@ -112,7 +115,11 @@ void * thread_main(void *arg) {
     while(running) {
         socket_wait = time(0) + SOCKET_SELECT_TIME;
         do {
-            socket_loop(SOCKET_SELECT_TIME);
+            if(!socket_loop(SOCKET_SELECT_TIME)) {
+                putlog(LOGLEVEL_ERROR, "No more active Bots... shutting down.");
+                cleanup();
+                exit(0);
+            }
         } while(time(0) < socket_wait);
         clearTempUsers();
         destroyEvents();
@@ -143,38 +150,57 @@ void exit_daemon() {
     if(daemonized) {
         remove(PID_FILE);
     }
+    if(log_fptr) {
+        fclose(log_fptr);
+        log_fptr = NULL;
+    }
 }
 
 int main(int argc, char *argv[]) {
     int run_as_daemon = 1;
-    int argi;
+    int c;
     process_argv = argv;
     process_argc = argc;
     printf("NeonServ v%s\n\n", NEONSERV_VERSION);
-    for(argi = 1; argi < argc; argi++) {
-        if(!strcmp(argv[argi], "-f") || !strcmp(argv[argi], "--foreground")) {
+    struct option options[] = {
+        {"show", 1, 0, 's'},
+        {"foreground", 0, 0, 'f'},
+        {"help", 0, 0, 'h'},
+        {"version", 0, 0, 'v'},
+        {0, 0, 0, 0}
+    };
+    while ((c = getopt_long(argc, argv, "s:fvh", options, NULL)) != -1) {
+        switch (c) {
+        case 's':
+            print_loglevel = atoi(optarg);
+            break;
+        case 'f':
             run_as_daemon = 0;
-        } else if(!strcmp(argv[argi], "-s") || !strcmp(argv[argi], "--show")) {
-            if(argi+1 == argc) break;
-            argi++;
-            print_loglevel = atoi(argv[argi]);
-        } else if(!strcmp(argv[argi], "-v") || !strcmp(argv[argi], "--version")) {
+            break;
+        case 'v':
             printf("Version: %s.%d (%s)\n", NEONSERV_VERSION, patchlevel, (strcmp(revision, "") ? revision : "-"));
             printf("Build: #%s %s (%s lines, " COMPILER ")\n", compilation, creation, codelines);
             exit(0);
-        } else if(!strcmp(argv[argi], "-h") || !strcmp(argv[argi], "--help")) {
+            break;
+        case 'h':
             printf("Usage: ./neonserv [-s loglevel] [-f] [-h|-v]\n");
             printf(" -s, --show           show log lines matching loglevel in stdout.\n");
             printf(" -f, --foreground     run NeonServ in the foreground.\n");
             printf(" -h, --help           prints this usage message.\n");
             printf(" -v, --version        prints this program's version.\n");
             exit(0);
+            break;
         }
     }
+    #ifndef WIN32
     if(geteuid() == 0 || getuid() == 0) {
         fprintf(stderr, "NeonServ may not be run with super user privileges.\n");
         exit(0);
     }
+    #endif
+    #ifdef ENABLE_MEMORY_DEBUG
+    initMemoryDebug();
+    #endif
     if(!loadConfig(CONF_FILE)) {
         fprintf(stderr, "Unable to load " CONF_FILE "\n");
         exit(0);
@@ -182,7 +208,13 @@ int main(int argc, char *argv[]) {
     #if HAVE_THREADS
     THREAD_MUTEX_INIT(log_sync);
     #endif
+    if(!load_mysql_config()) {
+        fprintf(stderr, "Unable to connect to MySQL\n");
+        exit(0);
+    }
+    check_firstrun();
     if (run_as_daemon) {
+        #ifndef WIN32
         /* Attempt to fork into the background if daemon mode is on. */
         pid_t pid = fork();
         if (pid < 0) {
@@ -203,9 +235,10 @@ int main(int argc, char *argv[]) {
             fprintf(pidfile, "%i\n", (int)getpid());
             fclose(pidfile);
         }
-        fclose(stdin);
-        fclose(stdout);
-        fclose(stderr);
+        fclose(stdin); fopen("/dev/null", "r");
+        fclose(stdout); fopen("/dev/null", "w");
+        fclose(stderr); fopen("/dev/null", "w");
+        #endif
     }
     
 main:
@@ -216,10 +249,6 @@ main:
     signal(SIGSEGV, sighandler);
     signal(SIGTERM, sighandler);
     
-    #ifdef ENABLE_MEMORY_DEBUG
-    initMemoryDebug();
-    #endif
-    
     start_time = time(0);
     
     #ifdef WIN32
@@ -234,8 +263,6 @@ main:
     }
     #endif
     
-    if(!load_mysql_config()) return 0;
-    
     statistics_enabled = get_int_field("statistics.enable");
     
     #ifdef HAVE_THREADS
@@ -255,9 +282,10 @@ main:
     init_ModeNode();
     init_bind();
        init_modcmd();
+    register_module_commands();
     init_handleinfohandler();
     init_tools();
-    register_commands();
+    loadModules();
     init_bots();
     init_DBHelper();
     qserver_init();
@@ -265,9 +293,9 @@ main:
     load_languages();
     int update_minutes = get_int_field("statistics.frequency");
     if(!update_minutes) update_minutes = 2;
-    timeq_add(update_minutes * 60 + 10, main_statistics, NULL);
+    timeq_add(update_minutes * 60 + 10, 0, main_statistics, NULL);
     
-    timeq_add(90, main_checkauths, NULL);
+    timeq_add(90, 0, main_checkauths, NULL);
     
     int worker_threads = get_int_field("General.worker_threads");
     if(!worker_threads) worker_threads = 1;
@@ -282,7 +310,7 @@ main:
     int usleep_delay = 1000000 / TICKS_PER_SECOND;
     while(running) {
         timeq_tick();
-        loop_bots();
+        loop_modules();
         qserver_loop();
         queue_loop();
         mysql_free();
@@ -297,10 +325,14 @@ main:
     while(running) {
         socket_wait = time(0) + SOCKET_SELECT_TIME;
         do {
-            socket_loop(SOCKET_SELECT_TIME);
+            if(!socket_loop(SOCKET_SELECT_TIME)) {
+                putlog(LOGLEVEL_ERROR, "No more active Bots... shutting down.");
+                cleanup();
+                exit(0);
+            }
         } while(time(0) < socket_wait);
         timeq_tick();
-        loop_bots();
+        loop_modules();
         clearTempUsers();
         destroyEvents();
         qserver_loop();
@@ -428,7 +460,7 @@ TIMEQ_CALLBACK(main_checkauths) {
             if ((row = mysql_fetch_row(res)) != NULL) {
                 lastcheck = atoi(row[1]);
                 if(!lastcheck || unixtime - lastcheck >= min_unckecked) {
-                    lookup_authname(row[0], main_checkauths_callback, NULL);
+                    lookup_authname(row[0], 0, main_checkauths_callback, NULL);
                 } else 
                     next_call = 300;
             }
@@ -443,13 +475,13 @@ TIMEQ_CALLBACK(main_checkauths) {
         }
         
     }
-    timeq_add(next_call, main_checkauths, NULL);
+    timeq_add(next_call, 0, main_checkauths, NULL);
 }
 
 TIMEQ_CALLBACK(main_statistics) {
     int update_minutes = get_int_field("statistics.frequency");
     if(!update_minutes) update_minutes = 2;
-    timeq_add(update_minutes * 60, main_statistics, NULL);
+    timeq_add(update_minutes * 60, 0, main_statistics, NULL);
     if(get_int_field("statistics.enable")) {
         statistics_enabled = 1;
         statistics_requested_lusers = 1;
@@ -489,6 +521,14 @@ void statistics_update() {
     }
 }
 
+time_t getStartTime() {
+    return start_time;
+}
+
+int getRunningThreads() {
+    return running_threads;
+}
+
 void write_log(int loglevel, const char *line, int len) {
     SYNCHRONIZE(log_sync);
     if(!daemonized && (print_loglevel & loglevel)) {
@@ -527,3 +567,108 @@ void putlog(int loglevel, const char *text, ...) {
     write_log(loglevel, logBuf, pos);
 }
 
+static void check_firstrun() {
+    MYSQL_RES *res;
+    MYSQL_ROW row;
+    printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_access` = 1000 LIMIT 1");
+    res = mysql_use();
+    if (mysql_fetch_row(res) == NULL) {
+        //first run!
+        printf("No superuser found...\n");
+        check_firstrun_admin:
+        printf("AuthServ account name of admin user: ");
+        char *ptr;
+        char adminuser[31];
+        fgets(adminuser, 30, stdin);
+        for(ptr = adminuser; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
+        if(strlen(adminuser) < 2) goto check_firstrun_admin;
+        printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_user` = '%s'", escape_string(adminuser));
+        res = mysql_use();
+        if ((row = mysql_fetch_row(res)) != NULL)
+            printf_mysql_query("UPDATE `users` SET `user_access` = 1000 WHERE `user_id` = '%s'", row[0]);
+        else
+            printf_mysql_query("INSERT INTO `users` (`user_user`, `user_access`) VALUES ('%s', 1000)", escape_string(adminuser));
+    }
+    printf_mysql_query("SELECT `id` FROM `bots` WHERE `active` = 1 LIMIT 1");
+    res = mysql_use();
+    if (mysql_fetch_row(res) == NULL) {
+        //no bot active
+        printf("No active bot found...\n\n");
+        printf("ADD NEW BOT\n");
+        char *ptr;
+        char bot_nick[31];
+        check_firstrun_bot_nick:
+        printf("Nick: ");
+        fgets(bot_nick, 30, stdin);
+        for(ptr = bot_nick; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
+        if(strlen(bot_nick) < 2) goto check_firstrun_bot_nick;
+        char bot_ident[16];
+        check_firstrun_bot_ident:
+        printf("Ident: ");
+        fgets(bot_ident, 15, stdin);
+        for(ptr = bot_ident; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
+        if(strlen(bot_ident) < 2) goto check_firstrun_bot_ident;
+        char bot_realname[101];
+        check_firstrun_bot_realname:
+        printf("Realname: ");
+        fgets(bot_realname, 100, stdin);
+        for(ptr = bot_realname; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
+        if(strlen(bot_realname) < 2) goto check_firstrun_bot_realname;
+        char bot_server[101];
+        check_firstrun_bot_server:
+        printf("Server: [irc.onlinegamesnet.net] ");
+        fgets(bot_server, 100, stdin);
+        for(ptr = bot_server; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
+        if(*bot_server && strlen(bot_nick) < 5) goto check_firstrun_bot_server;
+        if(!*bot_server)
+            strcpy(bot_server, "irc.onlinegamesnet.net");
+        int bot_port;
+        char bot_port_buf[7];
+        printf("Port: [6667] ");
+        fgets(bot_port_buf, 6, stdin);
+        for(ptr = bot_port_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
+        if(!*bot_port_buf)
+            bot_port = 6667;
+        else
+            bot_port = atoi(bot_port_buf);
+        int bot_ssl;
+        char bot_ssl_buf[5];
+        check_firstrun_bot_ssl:
+        printf("SSL: [y/N] ");
+        fgets(bot_ssl_buf, 4, stdin);
+        for(ptr = bot_ssl_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
+        if(!*bot_ssl_buf || tolower(*bot_ssl_buf) == 'n')
+            bot_ssl = 0;
+        else if(tolower(*bot_ssl_buf) == 'y')
+            bot_ssl = 1;
+        else
+            goto check_firstrun_bot_ssl;
+        char bot_pass[101];
+        printf("Server Password: [] ");
+        fgets(bot_pass, 100, stdin);
+        for(ptr = bot_pass; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
+        int bot_maxchan;
+        char bot_maxchan_buf[5];
+        printf("MaxChannel: [20] ");
+        fgets(bot_maxchan_buf, 5, stdin);
+        for(ptr = bot_maxchan_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
+        if(*bot_maxchan_buf)
+            bot_maxchan = atoi(bot_maxchan_buf);
+        else
+            bot_maxchan = 20;
+        int bot_queue;
+        char bot_queue_buf[5];
+        check_firstrun_bot_queue:
+        printf("Queue (prevents excess floods): [Y/n] ");
+        fgets(bot_queue_buf, 4, stdin);
+        for(ptr = bot_queue_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
+        if(!*bot_queue_buf || tolower(*bot_queue_buf) == 'y')
+            bot_queue = 1;
+        else if(tolower(*bot_queue_buf) == 'n')
+            bot_queue = 0;
+        else
+            goto check_firstrun_bot_queue;
+        printf_mysql_query("INSERT INTO `bots` (`active`, `nick`, `server`, `port`, `pass`, `ssl`, `ident`, `realname`, `botclass`, `textbot`, `queue`, `defaulttrigger`, `max_channels`) VALUES ('1', '%s', '%s', '%d', '%s', '%d', '%s', '%s', '1', '1', '%d', '+', '%d')", escape_string(bot_nick), escape_string(bot_server), bot_port, escape_string(bot_pass), bot_ssl, escape_string(bot_ident), escape_string(bot_realname), bot_queue, bot_maxchan);
+    }
+}
+