1 /* main.c - NeonServ v5.4
2 * Copyright (C) 2011-2012 Philipp Kreil (pk910)
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.
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.
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/>.
20 #include "ClientSocket.h"
23 #include "IRCEvents.h"
24 #include "IRCParser.h"
26 #include "WHOHandler.h"
28 #include "mysqlConn.h"
29 #include "HandleInfoHandler.h"
33 #include "EventLogger.h"
37 #include "ConfigParser.h"
42 #include "module_commands.h"
45 static int running, hard_restart;
46 static int statistics_requested_lusers = 0;
47 int statistics_enabled;
48 TIMEQ_CALLBACK(main_statistics);
49 TIMEQ_CALLBACK(main_checkauths);
50 static int daemonized = 0;
51 static int print_loglevel = 0;
52 static FILE *log_fptr = NULL;
53 static int process_argc;
54 static char **process_argv;
57 pthread_mutex_t cache_sync;
58 pthread_mutex_t whohandler_sync, whohandler_mass_sync;
59 static pthread_mutex_t log_sync;
62 static void check_firstrun();
75 free_handleinfohandler();
79 static int load_mysql_config() {
80 char *mysql_host, *mysql_user, *mysql_pass, *mysql_base;
83 mysql_host = get_string_field("MySQL.host");
85 perror("invalid neonserv.conf: missing MySQL.host");
88 mysql_serverport = get_int_field("MySQL.port");
90 mysql_serverport = 3306;
91 mysql_user = get_string_field("MySQL.user");
93 perror("invalid neonserv.conf: missing MySQL.user");
96 mysql_pass = get_string_field("MySQL.pass");
98 perror("invalid neonserv.conf: missing MySQL.pass");
101 mysql_base = get_string_field("MySQL.base");
103 perror("invalid neonserv.conf: missing MySQL base");
106 init_mysql(mysql_host, mysql_serverport, mysql_user, mysql_pass, mysql_base);
111 pthread_t *current_threads = NULL;
113 void * thread_main(void *arg) {
116 socket_wait = time(0) + SOCKET_SELECT_TIME;
118 if(!socket_loop(SOCKET_SELECT_TIME)) {
120 putlog(LOGLEVEL_ERROR, "No more active Bots... shutting down.\n");
124 } while(time(0) < socket_wait);
134 int getCurrentThreadID() {
135 if(!current_threads) return 0;
137 unsigned int my_tid = (unsigned int) pthread_self_tid();
138 for(i = 0; i < running_threads; i++) {
140 if((unsigned int) current_threads[i].p == my_tid)
142 if((unsigned int) current_threads[i] == my_tid)
162 int main(int argc, char *argv[]) {
163 int run_as_daemon = 1;
167 printf("NeonServ v%s\n\n", NEONSERV_VERSION);
168 struct option options[] = {
170 {"foreground", 0, 0, 'f'},
172 {"version", 0, 0, 'v'},
175 while ((c = getopt_long(argc, argv, "s:fvh", options, NULL)) != -1) {
178 print_loglevel = atoi(optarg);
184 printf("Version: %s.%d (%s)\n", NEONSERV_VERSION, patchlevel, (strcmp(revision, "") ? revision : "-"));
185 printf("Build: #%s %s (%s lines, " COMPILER ")\n", compilation, creation, codelines);
189 printf("Usage: ./neonserv [-s loglevel] [-f] [-h|-v]\n");
190 printf(" -s, --show show log lines matching loglevel in stdout.\n");
191 printf(" -f, --foreground run NeonServ in the foreground.\n");
192 printf(" -h, --help prints this usage message.\n");
193 printf(" -v, --version prints this program's version.\n");
199 if(geteuid() == 0 || getuid() == 0) {
200 fprintf(stderr, "NeonServ may not be run with super user privileges.\n");
204 #ifdef ENABLE_MEMORY_DEBUG
207 if(!loadConfig(CONF_FILE)) {
208 fprintf(stderr, "Unable to load " CONF_FILE "\n");
212 THREAD_MUTEX_INIT(log_sync);
214 if(!load_mysql_config()) {
215 fprintf(stderr, "Unable to connect to MySQL\n");
219 char **modulelist = get_all_fieldnames("modules");
220 if(!modulelist || !modulelist[0]) {
221 fprintf(stderr, "no modules loaded... Please update your configuration!\n");
227 /* Attempt to fork into the background if daemon mode is on. */
230 fprintf(stderr, "Unable to fork: %s\n", strerror(errno));
231 } else if (pid > 0) {
232 printf("Forking into the background (pid: %d)...\n", pid);
233 putlog(LOGLEVEL_INFO, "Forking into the background (pid: %d)...\n", pid);
239 FILE *pidfile = fopen(PID_FILE, "w");
240 if (pidfile == NULL) {
241 fprintf(stderr, "Unable to create PID file: %s\n", strerror(errno));
242 putlog(LOGLEVEL_ERROR, "Unable to create PID file: %s\n", strerror(errno));
244 fprintf(pidfile, "%i\n", (int)getpid());
248 fclose(stdin); retn = fopen("/dev/null", "r");
249 fclose(stdout); retn = fopen("/dev/null", "w");
250 fclose(stderr); retn = fopen("/dev/null", "w");
255 signal(SIGABRT, sighandler);
256 signal(SIGFPE, sighandler);
257 signal(SIGILL, sighandler);
258 signal(SIGINT, sighandler);
259 signal(SIGSEGV, sighandler);
260 signal(SIGTERM, sighandler);
262 start_time = time(0);
267 // Start Windows Sockets.
268 res = WSAStartup(MAKEWORD(2, 0), &wsadata);
271 perror("Unable to start Windows Sockets");
276 statistics_enabled = get_int_field("statistics.enable");
279 THREAD_MUTEX_INIT(cache_sync);
280 THREAD_MUTEX_INIT(whohandler_sync);
281 THREAD_MUTEX_INIT(whohandler_mass_sync);
295 register_module_commands();
296 init_handleinfohandler();
304 int update_minutes = get_int_field("statistics.frequency");
305 if(!update_minutes) update_minutes = 2;
306 timeq_add(update_minutes * 60 + 10, 0, main_statistics, NULL);
308 timeq_add(90, 0, main_checkauths, NULL);
310 int worker_threads = get_int_field("General.worker_threads");
311 if(!worker_threads) worker_threads = 1;
315 current_threads = calloc(worker_threads, sizeof(*current_threads));
316 for(tid_id = 0; tid_id < worker_threads; tid_id++) {
318 pthread_create(¤t_threads[tid_id], NULL, thread_main, NULL);
320 int usleep_delay = 1000000 / TICKS_PER_SECOND;
327 usleep(usleep_delay);
329 for(tid_id = 0; tid_id < worker_threads; tid_id++) {
330 pthread_join(current_threads[tid_id], NULL);
336 socket_wait = time(0) + SOCKET_SELECT_TIME;
338 if(!socket_loop(SOCKET_SELECT_TIME)) {
339 putlog(LOGLEVEL_ERROR, "No more active Bots... shutting down.\n");
343 } while(time(0) < socket_wait);
360 void restart_process() {
361 /* Append a NULL to the end of argv[]. */
362 char **restart_argv = (char **)alloca((process_argc + 1) * sizeof(char *));
363 memcpy(restart_argv, process_argv, process_argc * sizeof(char *));
364 restart_argv[process_argc] = NULL;
366 execv(process_argv[0], (const char * const*)restart_argv);
368 execv(process_argv[0], restart_argv);
372 int stricmp (const char *s1, const char *s2)
374 if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
375 if (s2 == NULL) return *s1;
377 while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
379 if (*s1 == '\0') break;
385 int stricmplen (const char *s1, const char *s2, int len)
387 if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
388 if (s2 == NULL) return *s1;
391 while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
394 if (*s1 == '\0') break;
401 void restart_bot(int do_hard_restart) {
402 hard_restart = do_hard_restart;
411 void reload_config() {
412 loadConfig(CONF_FILE);
415 static int getCurrentSecondsOfDay() {
416 time_t now = time(0);
417 struct tm *timeofday = localtime(&now);
419 seconds += timeofday->tm_hour * 3600;
420 seconds += timeofday->tm_min * 60;
421 seconds += timeofday->tm_sec;
425 static AUTHLOOKUP_CALLBACK(main_checkauths_callback) {
426 //check if registered is still valid
429 printf_mysql_query("SELECT `user_id`, `user_registered` FROM `users` WHERE `user_user` = '%s'", escape_string(auth));
431 if ((row = mysql_fetch_row(res)) != NULL) {
432 if(!exists || (strcmp(row[1], "0") && registered != atoi(row[1]))) {
433 //User is no longer valid! Delete it...
434 deleteUser(atoi(row[0]));
435 char *alertchan = get_string_field("General.CheckAuths.alertchan");
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", alertchan_chan->name, auth);
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]);
446 printf_mysql_query("UPDATE `users` SET `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", row[0]);
451 TIMEQ_CALLBACK(main_checkauths) {
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;
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"
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");
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);
479 if(now > check_start_time)
480 pending = 86400 - now + check_start_time;
482 pending = check_start_time - now;
488 timeq_add(next_call, 0, main_checkauths, NULL);
491 TIMEQ_CALLBACK(main_statistics) {
492 int update_minutes = get_int_field("statistics.frequency");
493 if(!update_minutes) update_minutes = 2;
494 timeq_add(update_minutes * 60, 0, main_statistics, NULL);
495 if(get_int_field("statistics.enable")) {
496 statistics_enabled = 1;
497 statistics_requested_lusers = 1;
498 if(get_int_field("statistics.include_lusers")) {
499 struct ClientSocket *bot, *lusersbot = NULL;
500 for(bot = getBots(SOCKET_FLAG_READY, NULL); bot; bot = getBots(SOCKET_FLAG_READY, bot)) {
501 if(bot->flags & SOCKET_FLAG_PREFERRED)
505 if(bot == NULL) bot = getBots(SOCKET_FLAG_READY, NULL);
506 putsock(bot, "LUSERS");
511 statistics_enabled = 0;
514 int statistics_update() {
515 if(get_int_field("statistics.enable") && statistics_requested_lusers && get_string_field("statistics.execute")) {
516 statistics_requested_lusers = 0;
517 char command[MAXLEN];
523 - commands per minute
527 sprintf(command, "%s %d %d %d %d %d %d %d", get_string_field("statistics.execute"), getUserCount(), getChanUserCount(), getChannelCount(), statistics_privmsg, statistics_commands, statistics_network_users, statistics_network_channels);
528 statistics_privmsg = 0;
529 statistics_commands = 0;
530 return system(command);
535 time_t getStartTime() {
539 int getRunningThreads() {
541 return running_threads;
547 void write_log(int loglevel, const char *line, int len) {
548 SYNCHRONIZE(log_sync);
549 if(!daemonized && (print_loglevel & loglevel)) {
551 } else if(!daemonized && loglevel == LOGLEVEL_ERROR) {
552 fprintf(stderr, "%s", line);
554 if(get_int_field("log.loglevel") & loglevel) {
556 log_fptr = fopen(LOG_FILE, "a");
557 if(!log_fptr) goto write_log_end;
562 timeinfo = localtime(&rawtime);
564 int timepos = strftime(timestr, 20, "%x %X ", timeinfo);
565 fwrite(timestr, 1, timepos, log_fptr);
566 fwrite(line, 1, len, log_fptr);
569 DESYNCHRONIZE(log_sync);
572 void putlog(int loglevel, const char *text, ...) {
574 char logBuf[MAXLOGLEN];
577 va_start(arg_list, text);
578 pos = vsnprintf(logBuf, MAXLOGLEN - 1, text, arg_list);
580 if (pos < 0 || pos > (MAXLOGLEN - 1)) pos = MAXLOGLEN - 1;
582 write_log(loglevel, logBuf, pos);
585 static void check_firstrun() {
588 printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_access` = 1000 LIMIT 1");
590 if (mysql_fetch_row(res) == NULL) {
592 printf("No superuser found...\n");
593 check_firstrun_admin:
594 printf("AuthServ account name of admin user: ");
597 ptr = fgets(adminuser, 30, stdin);
598 for(ptr = adminuser; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
599 if(strlen(adminuser) < 2) goto check_firstrun_admin;
600 printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_user` = '%s'", escape_string(adminuser));
602 if ((row = mysql_fetch_row(res)) != NULL)
603 printf_mysql_query("UPDATE `users` SET `user_access` = 1000 WHERE `user_id` = '%s'", row[0]);
605 printf_mysql_query("INSERT INTO `users` (`user_user`, `user_access`) VALUES ('%s', 1000)", escape_string(adminuser));
607 printf_mysql_query("SELECT `id` FROM `bots` WHERE `active` = 1 LIMIT 1");
609 if (mysql_fetch_row(res) == NULL) {
611 printf("No active bot found...\n\n");
612 printf("ADD NEW BOT\n");
615 check_firstrun_bot_nick:
617 ptr = fgets(bot_nick, 30, stdin);
618 for(ptr = bot_nick; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
619 if(strlen(bot_nick) < 2) goto check_firstrun_bot_nick;
621 check_firstrun_bot_ident:
623 ptr = fgets(bot_ident, 15, stdin);
624 for(ptr = bot_ident; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
625 if(strlen(bot_ident) < 2) goto check_firstrun_bot_ident;
626 char bot_realname[101];
627 check_firstrun_bot_realname:
628 printf("Realname: ");
629 ptr = fgets(bot_realname, 100, stdin);
630 for(ptr = bot_realname; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
631 if(strlen(bot_realname) < 2) goto check_firstrun_bot_realname;
632 char bot_server[101];
633 check_firstrun_bot_server:
634 printf("Server: [irc.onlinegamesnet.net] ");
635 ptr = fgets(bot_server, 100, stdin);
636 for(ptr = bot_server; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
637 if(*bot_server && strlen(bot_nick) < 5) goto check_firstrun_bot_server;
639 strcpy(bot_server, "irc.onlinegamesnet.net");
641 char bot_port_buf[7];
642 printf("Port: [6667] ");
643 ptr = fgets(bot_port_buf, 6, stdin);
644 for(ptr = bot_port_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
648 bot_port = atoi(bot_port_buf);
651 check_firstrun_bot_ssl:
652 printf("SSL: [y/N] ");
653 ptr = fgets(bot_ssl_buf, 4, stdin);
654 for(ptr = bot_ssl_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
655 if(!*bot_ssl_buf || tolower(*bot_ssl_buf) == 'n')
657 else if(tolower(*bot_ssl_buf) == 'y')
660 goto check_firstrun_bot_ssl;
662 printf("Server Password: [] ");
663 ptr = fgets(bot_pass, 100, stdin);
664 for(ptr = bot_pass; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
666 char bot_maxchan_buf[5];
667 printf("MaxChannel: [20] ");
668 ptr = fgets(bot_maxchan_buf, 5, stdin);
669 for(ptr = bot_maxchan_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
671 bot_maxchan = atoi(bot_maxchan_buf);
675 char bot_queue_buf[5];
676 check_firstrun_bot_queue:
677 printf("Queue (prevents excess floods): [Y/n] ");
678 ptr = fgets(bot_queue_buf, 4, stdin);
679 for(ptr = bot_queue_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
680 if(!*bot_queue_buf || tolower(*bot_queue_buf) == 'y')
682 else if(tolower(*bot_queue_buf) == 'n')
685 goto check_firstrun_bot_queue;
686 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);