fixed small compilation errors (debug mode)
[NeonServV5.git] / src / main.c
1 /* main.c - NeonServ v5.6
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 #define DEFAULT_PID_FILE "neonserv.pid"
19 #define DEFAULT_CONF_FILE "neonserv.conf"
20
21 #include "main.h"
22 #include "signal.h"
23 #include "ClientSocket.h"
24 #include "UserNode.h"
25 #include "ChanNode.h"
26 #include "IRCEvents.h"
27 #include "IRCParser.h"
28 #include "modcmd.h"
29 #include "WHOHandler.h"
30 #include "bots.h"
31 #include "mysqlConn.h"
32 #include "HandleInfoHandler.h"
33 #include "lang.h"
34 #include "tools.h"
35 #include "timeq.h"
36 #include "EventLogger.h"
37 #include "ModeNode.h"
38 #include "IRCQueue.h"
39 #include "DBHelper.h"
40 #include "ConfigParser.h"
41 #include "QServer.h"
42 #include "version.h"
43 #include "modules.h"
44 #include "module_commands.h"
45 #include "ModuleFunctions.h"
46 #include "IOHandler.h"
47 #include "statistics.h"
48 #include "log.h"
49
50 struct ProcessState process_state;
51
52 #ifdef HAVE_THREADS
53 pthread_mutex_t cache_sync;
54 pthread_mutex_t whohandler_sync, whohandler_mass_sync;
55 static pthread_t *current_threads = NULL;
56 #endif
57
58 static void *main_tread(void *empty);
59 static TIMEQ_CALLBACK(clear_cache);
60 static TIMEQ_CALLBACK(main_checkauths);
61 static void check_firstrun();
62
63
64 static void main_parse_arguments() {
65     int c;
66     struct option options[] = {
67         {"show", 1, 0, 's'},
68         {"foreground", 0, 0, 'f'},
69         {"config", 1, 0, 'c'},
70         {"pid", 1, 0, 'p'},
71         {"help", 0, 0, 'h'},
72         {"version", 0, 0, 'v'},
73         {0, 0, 0, 0}
74     };
75     while ((c = getopt_long(process_state.argc, process_state.argv, "s:fvh", options, NULL)) != -1) {
76         switch (c) {
77         case 'c':
78             strncpy(process_state.config, optarg, MAXLEN-1);
79             break;
80         case 'p':
81             strncpy(process_state.pidfile, optarg, MAXLEN-1);
82             break;
83         case 's':
84             process_state.loglevel = atoi(optarg);
85             break;
86         case 'f':
87             process_state.run_as_daemon = 0;
88             break;
89         case 'v':
90             printf("Version: %s.%d (%s)\n", NEONSERV_VERSION, patchlevel, (strcmp(revision, "") ? revision : "-"));
91             printf("Build: #%s %s (%s lines, " COMPILER ")\n", compilation, creation, codelines);
92             exit(0);
93             break;
94         case 'h':
95             printf("Usage: ./neonserv [-c neonserv.conf] [-p neonserv.pid] [-s loglevel] [-f] [-h|-v]\n");
96             printf(" -c, --config         use this configuration file.\n");
97             printf(" -f, --foreground     run NeonServ in the foreground.\n");
98             printf(" -h, --help           prints this usage message.\n");
99             printf(" -p, --pid            use this pid file.\n");
100             printf(" -s, --show           show log lines matching loglevel in stdout.\n");
101             printf(" -v, --version        prints this program's version.\n");
102             exit(0);
103             break;
104         }
105     }
106 }
107
108 static void main_daemon_exit() {
109     remove(process_state.pidfile);
110 }
111
112 static void main_daemonize() {
113     #ifndef WIN32
114     /* Attempt to fork into the background if daemon mode is on. */
115     pid_t pid = fork();
116     if (pid < 0) {
117         fprintf(stderr, "Unable to fork: %s\n", strerror(errno));
118     } else if (pid > 0) {
119         printf("Forking into the background (pid: %d)...\n", pid);
120         printf_log("main", LOG_INFO, "Forking into the background (pid: %d)...\n", pid);
121         exit(0);
122     }
123     setsid();
124     process_state.daemonized = 1;
125     atexit(main_daemon_exit);
126     FILE *pidfile = fopen(process_state.pidfile, "w");
127     if (pidfile == NULL) {
128         fprintf(stderr, "Unable to create PID file: %s\n", strerror(errno));
129         printf_log("main", LOG_ERROR, "Unable to create PID file: %s\n", strerror(errno));
130     } else {
131         fprintf(pidfile, "%i\n", (int)getpid());
132         fclose(pidfile);
133     }
134     fclose(stdin); fopen("/dev/null", "r");
135     fclose(stdout); fopen("/dev/null", "w");
136     fclose(stderr); fopen("/dev/null", "w");
137     #endif
138 }
139
140 static int reload_configuration() {
141     printf_log("main", LOG_DEBUG, "reloading configuration file: %s", process_state.config);
142     if(!loadConfig(process_state.config)) {
143         printf_log("main", LOG_ERROR, "could not reload configuration file: %s", process_state.config);
144         return 1;
145     }
146     if(process_state.loaded_config) {
147         if(!reload_mysql())
148             return 2;
149         char **modulelist = get_all_fieldnames("modules");
150         if(!modulelist || !modulelist[0]) {
151             free(modulelist);
152             return 3;
153         }
154         free(modulelist);
155         event_reload(0);
156     }
157     process_state.loaded_config = 1;
158     return 0;
159 }
160
161
162 /* INITIALISATION OF SUBSYSTEMS */
163 void initialize_subsystems() {
164     init_bind();
165     init_log();
166     printf_log("main", LOG_INFO, "starting up NeonServ %s subsystems...", NEONSERV_VERSION);
167     init_lang();
168     init_parser();
169     init_UserNode();
170     init_ChanNode();
171     init_ModeNode();
172         init_modcmd();
173     register_module_commands();
174     init_handleinfohandler();
175     init_tools();
176     init_modulefunctions();
177     loadModules();
178     init_bots();
179     init_DBHelper();
180     qserver_init();
181     load_languages();
182     init_statistics();
183 }
184
185 void shutdown_subsystems() {
186     printf_log("main", LOG_INFO, "stopping NeonServ subsystems...");
187     free_sockets(1);
188     //wait 50ms (run iohandler)
189     {
190         struct timeval timeout, ctime1, ctime2;
191         gettimeofday(&ctime1, NULL);
192         ctime1.tv_usec += 50000;
193         if(ctime1.tv_usec > 1000000) {
194             ctime1.tv_usec -= 1000000;
195             ctime1.tv_sec++;
196         }
197         do {
198             timeout.tv_sec = 0;
199             timeout.tv_usec = 10000;
200             iohandler_poll_timeout(timeout);
201             gettimeofday(&ctime2, NULL);
202         } while(timeval_is_bigger(ctime1, ctime2));
203     }
204     stop_modules();
205     free_sockets(0);
206     qserver_free();
207     free_parser();
208     free_UserNode();
209     free_ChanNode();
210     free_bind();
211     free_modcmd();
212     free_whoqueue();
213     free_mysql();
214     free_handleinfohandler();
215     free_lang();
216 }
217
218 /* THREAD CONTROL */
219 #ifdef HAVE_THREADS
220 int getCurrentThreadID() {
221     if(!current_threads) return 0;
222     int i;
223     unsigned int my_tid = (unsigned int) pthread_self_tid();
224     for(i = 0; i < process_state.running_threads; i++) {
225         #ifdef WIN32
226         if((unsigned int) current_threads[i].p == my_tid)
227         #else
228         if((unsigned int) current_threads[i] == my_tid)
229         #endif
230             return i+1;
231     }
232     return 0;
233 }
234 #endif
235
236 int getRunningThreads() {
237         #ifdef HAVE_THREADS
238     return process_state.running_threads;
239         #else
240         return 1;
241         #endif
242 }
243
244 static void main_start_threads() {
245     int worker_threads = get_int_field("General.worker_threads");
246     if(!worker_threads) worker_threads = 1;
247     #ifdef HAVE_THREADS
248     int tid_id = 0;
249     {
250         current_threads = calloc(worker_threads, sizeof(*current_threads));
251         for(tid_id = 0; tid_id < worker_threads; tid_id++) {
252             process_state.running_threads++;
253             pthread_create(&current_threads[tid_id], NULL, main_tread, NULL);
254         }
255     }
256     #endif
257     main_tread(NULL);
258     #ifdef HAVE_THREADS
259     {
260         for(tid_id = 0; tid_id < worker_threads; tid_id++) {
261             pthread_join(current_threads[tid_id], NULL);
262         }
263         process_state.running_threads = 0;
264     }
265     #endif
266 }
267
268 /* MAIN FUNCTION(S) */
269
270 static void *main_tread(void *empty) {
271     while(process_state.running) {
272         iohandler_poll();
273     }
274     return NULL;
275 }
276
277 static void main_restart_process() {
278     /* Append a NULL to the end of argv[]. */
279     char **restart_argv = (char **)alloca((process_state.argc + 1) * sizeof(char *));
280     memcpy(restart_argv, process_state.argv, process_state.argc * sizeof(char *));
281     restart_argv[process_state.argc] = NULL;
282     #ifdef WIN32
283     execv(process_state.argv[0], (const char * const*)restart_argv);
284     #else
285     execv(process_state.argv[0], restart_argv);
286     #endif
287 }
288
289 int main(int argc, char *argv[]) {
290     memset(&process_state, 0, sizeof(process_state));
291     printf("NeonServ v%s\n\n", NEONSERV_VERSION);
292     
293     process_state.argv = argv;
294     process_state.argc = argc;
295     process_state.run_as_daemon = 1;
296     strcpy(process_state.config, DEFAULT_CONF_FILE);
297     strcpy(process_state.pidfile, DEFAULT_PID_FILE);
298     
299     //parse argv
300     main_parse_arguments();
301     
302     //initialize memory debugger BEFORE allocating memory
303     #ifdef ENABLE_MEMORY_DEBUG
304     initMemoryDebug();
305     #endif
306     
307     //initialize mutex debugger BEFORE using any mutexes
308     #ifdef ENABLE_MUTEX_DEBUG
309     initMutexDebug();
310     #endif
311     
312     //deny root startup
313     #ifndef WIN32
314     if(geteuid() == 0 || getuid() == 0) {
315         fprintf(stderr, "NeonServ may not be run with super user privileges.\n");
316         exit(0);
317     }
318     #endif
319     
320     //load configuration
321     int errid;
322     if((errid = reload_configuration())) {
323         fprintf(stderr, "Unable to load configuration file `%s`. (errid: %d)\n", process_state.config, errid);
324         exit(0);
325     }
326     
327     //check mysql configuration
328     if(!reload_mysql()) {
329         fprintf(stderr, "Unable to load MySQL configuration.\n");
330         exit(0);
331     }
332     
333     //check module configuration
334     char **modulelist = get_all_fieldnames("modules");
335     if(!modulelist || !modulelist[0]) {
336         fprintf(stderr, "Unable to load Module configuration.\n");
337         exit(0);
338     }
339     free(modulelist);
340     
341     #if HAVE_THREADS
342     THREAD_MUTEX_INIT(cache_sync);
343     THREAD_MUTEX_INIT(whohandler_sync);
344     THREAD_MUTEX_INIT(whohandler_mass_sync);
345     #endif
346     
347     //connect to mysql and check if it's the frst bot startup
348     init_mysql();
349     check_firstrun();
350     
351     //deamonize if wanted
352     if(process_state.run_as_daemon)
353         main_daemonize();
354     
355     //set signal handlers
356     signal(SIGABRT, sighandler);
357     signal(SIGFPE, sighandler);
358     signal(SIGILL, sighandler);
359     signal(SIGINT, sighandler);
360     signal(SIGSEGV, sighandler);
361     signal(SIGTERM, sighandler);
362     
363     //set start time and initialize other code parts
364     process_state.running = 1;
365     process_state.start_time = time(0);
366     initialize_subsystems();
367     
368     //start timers
369     timeq_add(CLEAR_CACHE_INTERVAL, 0, clear_cache, NULL);
370     timeq_add(90, 0, main_checkauths, NULL);
371     
372     //start worker threads
373     main_start_threads();  //BLOCKING
374     
375     //shutdown sequence...
376     shutdown_subsystems();
377     if(process_state.restart)
378         main_restart_process(); //terminates the current process on success
379     
380     //eop (end of program :P)
381     //trust me, thats the end!
382     exit(0);
383 }
384
385 /* BOT INFORMATION */
386 time_t getStartTime() {
387     return process_state.start_time;
388 }
389
390 /* BOT CONTROL */
391 void restart_bot(int crash) {
392     if(crash) {
393         main_daemon_exit();
394         main_restart_process();
395     } else {
396         process_state.restart = 1;
397         process_state.running = 0;
398     }
399 }
400
401 void stop_bot() {
402     process_state.running = 0;
403 }
404
405 void reload_config() {
406     reload_configuration();
407 }
408
409 /* TIMER FUNCTIONS */
410
411 static TIMEQ_CALLBACK(clear_cache) {
412     timeq_add(CLEAR_CACHE_INTERVAL, 0, clear_cache, NULL);
413     clearTempUsers();
414     destroyEvents();
415     mysql_free();
416 }
417
418 static AUTHLOOKUP_CALLBACK(main_checkauths_callback) {
419     //check if registered is still valid
420     MYSQL_RES *res;
421     MYSQL_ROW row;
422     printf_mysql_query("SELECT `user_id`, `user_registered` FROM `users` WHERE `user_user` = '%s'", escape_string(auth));
423     res = mysql_use();
424     if ((row = mysql_fetch_row(res)) != NULL) {
425         int diff = registered - atoi(row[1]);
426         if(diff < 0)
427             diff *= -1;
428         if(!exists || (strcmp(row[1], "0") && diff > 86400)) {
429             //User is no longer valid! Delete it...
430             deleteUser(atoi(row[0]));
431             char *alertchan = get_string_field("General.CheckAuths.alertchan");
432             if(alertchan) {
433                 char reason[MAXLEN];
434                 if(!exists) {
435                     strcpy(reason, "USER_NOT_EXISTS");
436                 } else {
437                     sprintf(reason, "USER_REGISTERED_MISSMATCH: %lu, expected %d (diff: %d)", (unsigned long) registered, atoi(row[1]), diff);
438                 }
439                 struct ChanNode *alertchan_chan = getChanByName(alertchan);
440                 struct ClientSocket *alertclient;
441                 if(alertchan_chan && (alertclient = getChannelBot(alertchan_chan, 0)) != NULL) {
442                     putsock(alertclient, "PRIVMSG %s :Deleted User %s (%s)", alertchan_chan->name, auth, reason);
443                 }
444             }
445         } else if(exists && !strcmp(row[1], "0")) {
446             printf_mysql_query("UPDATE `users` SET `user_registered` = '%lu', `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", (unsigned long) registered, row[0]);
447         } else {
448             printf_mysql_query("UPDATE `users` SET `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", row[0]);
449         }
450     }
451 }
452
453 static TIMEQ_CALLBACK(main_checkauths) {
454     int next_call = 600;
455     if(get_int_field("General.CheckAuths.enabled")) {
456         int check_start_time = get_int_field("General.CheckAuths.start_time") * 3600;
457         int duration = get_int_field("General.CheckAuths.duration") * 60;
458         int now = getCurrentSecondsOfDay();
459         if(now < check_start_time && check_start_time+duration >= 86400) {
460             check_start_time -= 86400;
461         }
462         if(now >= check_start_time && now < (check_start_time + duration)) {
463             next_call = get_int_field("General.CheckAuths.interval");
464             //get the "longest-unchecked-user"
465             MYSQL_RES *res;
466             MYSQL_ROW row;
467             int lastcheck;
468             time_t unixtime = time(0);
469             int min_unckecked = get_int_field("General.CheckAuths.min_unckecked");
470             printf_mysql_query("SELECT `user_user`, `user_lastcheck` FROM `users` ORDER BY `user_lastcheck` ASC LIMIT 1");
471             res = mysql_use();
472             if ((row = mysql_fetch_row(res)) != NULL) {
473                 lastcheck = atoi(row[1]);
474                 if(!lastcheck || unixtime - lastcheck >= min_unckecked) {
475                     lookup_authname(row[0], 0, main_checkauths_callback, NULL);
476                 } else 
477                     next_call = 300;
478             }
479         } else {
480             int pending;
481             if(now > check_start_time)
482                 pending = 86400 - now + check_start_time;
483             else
484                 pending = check_start_time - now;
485             if(pending < 600)
486                 next_call = pending;
487         }
488         
489     }
490     timeq_add(next_call, 0, main_checkauths, NULL);
491 }
492
493 /* INSTALLATION SCRIPT */
494
495 static void check_firstrun() {
496     MYSQL_RES *res;
497     MYSQL_ROW row;
498     printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_access` = 1000 LIMIT 1");
499     res = mysql_use();
500     if (mysql_fetch_row(res) == NULL) {
501         //first run!
502         printf("No superuser found...\n");
503         check_firstrun_admin:
504         printf("AuthServ account name of admin user: ");
505         char *ptr;
506         char adminuser[31];
507         ptr = fgets(adminuser, 30, stdin);
508         for(ptr = adminuser; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
509         if(strlen(adminuser) < 2) goto check_firstrun_admin;
510         printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_user` = '%s'", escape_string(adminuser));
511         res = mysql_use();
512         if ((row = mysql_fetch_row(res)) != NULL)
513             printf_mysql_query("UPDATE `users` SET `user_access` = 1000 WHERE `user_id` = '%s'", row[0]);
514         else
515             printf_mysql_query("INSERT INTO `users` (`user_user`, `user_access`) VALUES ('%s', 1000)", escape_string(adminuser));
516     }
517     printf_mysql_query("SELECT `id` FROM `bots` WHERE `active` = 1 LIMIT 1");
518     res = mysql_use();
519     if (mysql_fetch_row(res) == NULL) {
520         //no bot active
521         printf("No active bot found...\n\n");
522         printf("ADD NEW BOT\n");
523         char *ptr;
524         char bot_nick[31];
525         check_firstrun_bot_nick:
526         printf("Nick: ");
527         ptr = fgets(bot_nick, 30, stdin);
528         for(ptr = bot_nick; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
529         if(strlen(bot_nick) < 2) goto check_firstrun_bot_nick;
530         char bot_ident[16];
531         check_firstrun_bot_ident:
532         printf("Ident: ");
533         ptr = fgets(bot_ident, 15, stdin);
534         for(ptr = bot_ident; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
535         if(strlen(bot_ident) < 2) goto check_firstrun_bot_ident;
536         char bot_realname[101];
537         check_firstrun_bot_realname:
538         printf("Realname: ");
539         ptr = fgets(bot_realname, 100, stdin);
540         for(ptr = bot_realname; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
541         if(strlen(bot_realname) < 2) goto check_firstrun_bot_realname;
542         char bot_server[101];
543         check_firstrun_bot_server:
544         printf("Server: [irc.onlinegamesnet.net] ");
545         ptr = fgets(bot_server, 100, stdin);
546         for(ptr = bot_server; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
547         if(*bot_server && strlen(bot_nick) < 5) goto check_firstrun_bot_server;
548         if(!*bot_server)
549             strcpy(bot_server, "irc.onlinegamesnet.net");
550         int bot_port;
551         char bot_port_buf[7];
552         printf("Port: [6667] ");
553         ptr = fgets(bot_port_buf, 6, stdin);
554         for(ptr = bot_port_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
555         if(!*bot_port_buf)
556             bot_port = 6667;
557         else
558             bot_port = atoi(bot_port_buf);
559         int bot_ssl;
560         char bot_ssl_buf[5];
561         check_firstrun_bot_ssl:
562         printf("SSL: [y/N] ");
563         ptr = fgets(bot_ssl_buf, 4, stdin);
564         for(ptr = bot_ssl_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
565         if(!*bot_ssl_buf || tolower(*bot_ssl_buf) == 'n')
566             bot_ssl = 0;
567         else if(tolower(*bot_ssl_buf) == 'y')
568             bot_ssl = 1;
569         else
570             goto check_firstrun_bot_ssl;
571         char bot_pass[101];
572         printf("Server Password: [] ");
573         ptr = fgets(bot_pass, 100, stdin);
574         for(ptr = bot_pass; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
575         int bot_maxchan;
576         char bot_maxchan_buf[5];
577         printf("MaxChannel: [20] ");
578         ptr = fgets(bot_maxchan_buf, 5, stdin);
579         for(ptr = bot_maxchan_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
580         if(*bot_maxchan_buf)
581             bot_maxchan = atoi(bot_maxchan_buf);
582         else
583             bot_maxchan = 20;
584         int bot_queue;
585         char bot_queue_buf[5];
586         check_firstrun_bot_queue:
587         printf("Queue (prevents excess floods): [Y/n] ");
588         ptr = fgets(bot_queue_buf, 4, stdin);
589         for(ptr = bot_queue_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
590         if(!*bot_queue_buf || tolower(*bot_queue_buf) == 'y')
591             bot_queue = 1;
592         else if(tolower(*bot_queue_buf) == 'n')
593             bot_queue = 0;
594         else
595             goto check_firstrun_bot_queue;
596         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);
597     }
598 }
599