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