1 /* main.c - NeonServ v5.3
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"
38 #include "ConfigParser.h"
44 static int running, hard_restart;
45 static int statistics_requested_lusers = 0;
46 int statistics_enabled;
47 TIMEQ_CALLBACK(main_statistics);
48 TIMEQ_CALLBACK(main_checkauths);
49 static int daemonized = 0;
50 static int print_loglevel = 0;
51 static FILE *log_fptr = NULL;
52 static int process_argc;
53 static char **process_argv;
56 pthread_mutex_t cache_sync;
57 pthread_mutex_t whohandler_sync, whohandler_mass_sync;
58 static pthread_mutex_t log_sync;
61 static void check_firstrun();
74 free_handleinfohandler();
78 static int load_mysql_config() {
79 char *mysql_host, *mysql_user, *mysql_pass, *mysql_base;
82 mysql_host = get_string_field("MySQL.host");
84 perror("invalid neonserv.conf: missing MySQL.host");
87 mysql_serverport = get_int_field("MySQL.port");
89 mysql_serverport = 3306;
90 mysql_user = get_string_field("MySQL.user");
92 perror("invalid neonserv.conf: missing MySQL.user");
95 mysql_pass = get_string_field("MySQL.pass");
97 perror("invalid neonserv.conf: missing MySQL.pass");
100 mysql_base = get_string_field("MySQL.base");
102 perror("invalid neonserv.conf: missing MySQL base");
105 init_mysql(mysql_host, mysql_serverport, mysql_user, mysql_pass, mysql_base);
110 pthread_t *current_threads = NULL;
112 void * thread_main(void *arg) {
115 socket_wait = time(0) + SOCKET_SELECT_TIME;
117 if(!socket_loop(SOCKET_SELECT_TIME)) {
118 putlog(LOGLEVEL_ERROR, "No more active Bots... shutting down.");
122 } while(time(0) < socket_wait);
131 int getCurrentThreadID() {
132 if(!current_threads) return 0;
134 unsigned int my_tid = (unsigned int) pthread_self_tid();
135 for(i = 0; i < running_threads; i++) {
137 if((unsigned int) current_threads[i].p == my_tid)
139 if((unsigned int) current_threads[i] == my_tid)
154 int main(int argc, char *argv[]) {
155 int run_as_daemon = 1;
159 printf("NeonServ v%s\n\n", NEONSERV_VERSION);
160 for(argi = 1; argi < argc; argi++) {
161 if(!strcmp(argv[argi], "-f") || !strcmp(argv[argi], "--foreground")) {
163 } else if(!strcmp(argv[argi], "-s") || !strcmp(argv[argi], "--show")) {
164 if(argi+1 == argc) break;
166 print_loglevel = atoi(argv[argi]);
167 } else if(!strcmp(argv[argi], "-v") || !strcmp(argv[argi], "--version")) {
168 printf("Version: %s.%d (%s)\n", NEONSERV_VERSION, patchlevel, (strcmp(revision, "") ? revision : "-"));
169 printf("Build: #%s %s (%s lines, " COMPILER ")\n", compilation, creation, codelines);
171 } else if(!strcmp(argv[argi], "-h") || !strcmp(argv[argi], "--help")) {
172 printf("Usage: ./neonserv [-s loglevel] [-f] [-h|-v]\n");
173 printf(" -s, --show show log lines matching loglevel in stdout.\n");
174 printf(" -f, --foreground run NeonServ in the foreground.\n");
175 printf(" -h, --help prints this usage message.\n");
176 printf(" -v, --version prints this program's version.\n");
180 if(geteuid() == 0 || getuid() == 0) {
181 fprintf(stderr, "NeonServ may not be run with super user privileges.\n");
184 if(!loadConfig(CONF_FILE)) {
185 fprintf(stderr, "Unable to load " CONF_FILE "\n");
189 THREAD_MUTEX_INIT(log_sync);
191 if(!load_mysql_config()) {
192 fprintf(stderr, "Unable to connect to MySQL\n");
197 /* Attempt to fork into the background if daemon mode is on. */
200 fprintf(stderr, "Unable to fork: %s\n", strerror(errno));
201 } else if (pid > 0) {
202 printf("Forking into the background (pid: %d)...\n", pid);
203 putlog(LOGLEVEL_INFO, "Forking into the background (pid: %d)...\n", pid);
209 FILE *pidfile = fopen(PID_FILE, "w");
210 if (pidfile == NULL) {
211 fprintf(stderr, "Unable to create PID file: %s", strerror(errno));
212 putlog(LOGLEVEL_ERROR, "Unable to create PID file: %s", strerror(errno));
214 fprintf(pidfile, "%i\n", (int)getpid());
223 signal(SIGABRT, sighandler);
224 signal(SIGFPE, sighandler);
225 signal(SIGILL, sighandler);
226 signal(SIGINT, sighandler);
227 signal(SIGSEGV, sighandler);
228 signal(SIGTERM, sighandler);
230 #ifdef ENABLE_MEMORY_DEBUG
234 start_time = time(0);
239 // Start Windows Sockets.
240 res = WSAStartup(MAKEWORD(2, 0), &wsadata);
243 perror("Unable to start Windows Sockets");
248 statistics_enabled = get_int_field("statistics.enable");
251 THREAD_MUTEX_INIT(cache_sync);
252 THREAD_MUTEX_INIT(whohandler_sync);
253 THREAD_MUTEX_INIT(whohandler_mass_sync);
267 init_handleinfohandler();
275 int update_minutes = get_int_field("statistics.frequency");
276 if(!update_minutes) update_minutes = 2;
277 timeq_add(update_minutes * 60 + 10, main_statistics, NULL);
279 timeq_add(90, main_checkauths, NULL);
281 int worker_threads = get_int_field("General.worker_threads");
282 if(!worker_threads) worker_threads = 1;
286 current_threads = calloc(worker_threads, sizeof(*current_threads));
287 for(tid_id = 0; tid_id < worker_threads; tid_id++) {
289 pthread_create(¤t_threads[tid_id], NULL, thread_main, NULL);
291 int usleep_delay = 1000000 / TICKS_PER_SECOND;
298 usleep(usleep_delay);
300 for(tid_id = 0; tid_id < worker_threads; tid_id++) {
301 pthread_join(current_threads[tid_id], NULL);
307 socket_wait = time(0) + SOCKET_SELECT_TIME;
309 if(!socket_loop(SOCKET_SELECT_TIME)) {
310 putlog(LOGLEVEL_ERROR, "No more active Bots... shutting down.");
314 } while(time(0) < socket_wait);
331 void restart_process() {
332 /* Append a NULL to the end of argv[]. */
333 char **restart_argv = (char **)alloca((process_argc + 1) * sizeof(char *));
334 memcpy(restart_argv, process_argv, process_argc * sizeof(char *));
335 restart_argv[process_argc] = NULL;
337 execv(process_argv[0], (const char * const*)restart_argv);
339 execv(process_argv[0], restart_argv);
343 int stricmp (const char *s1, const char *s2)
345 if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
346 if (s2 == NULL) return *s1;
348 while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
350 if (*s1 == '\0') break;
356 int stricmplen (const char *s1, const char *s2, int len)
358 if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
359 if (s2 == NULL) return *s1;
362 while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
365 if (*s1 == '\0') break;
372 void restart_bot(int do_hard_restart) {
373 hard_restart = do_hard_restart;
382 void reload_config() {
383 loadConfig(CONF_FILE);
386 static int getCurrentSecondsOfDay() {
387 time_t now = time(0);
388 struct tm *timeofday = localtime(&now);
390 seconds += timeofday->tm_hour * 3600;
391 seconds += timeofday->tm_min * 60;
392 seconds += timeofday->tm_sec;
396 static AUTHLOOKUP_CALLBACK(main_checkauths_callback) {
397 //check if registered is still valid
400 printf_mysql_query("SELECT `user_id`, `user_registered` FROM `users` WHERE `user_user` = '%s'", escape_string(auth));
402 if ((row = mysql_fetch_row(res)) != NULL) {
403 if(!exists || (strcmp(row[1], "0") && registered != atoi(row[1]))) {
404 //User is no longer valid! Delete it...
405 deleteUser(atoi(row[0]));
406 char *alertchan = get_string_field("General.CheckAuths.alertchan");
408 struct ChanNode *alertchan_chan = getChanByName(alertchan);
409 struct ClientSocket *alertclient;
410 if(alertchan_chan && (alertclient = getChannelBot(alertchan_chan, 0)) != NULL) {
411 putsock(alertclient, "PRIVMSG %s :Deleted User %s", alertchan_chan->name, auth);
414 } else if(exists && !strcmp(row[1], "0")) {
415 printf_mysql_query("UPDATE `users` SET `user_registered` = '%lu', `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", (unsigned long) registered, row[0]);
417 printf_mysql_query("UPDATE `users` SET `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", row[0]);
422 TIMEQ_CALLBACK(main_checkauths) {
424 if(get_int_field("General.CheckAuths.enabled")) {
425 int check_start_time = get_int_field("General.CheckAuths.start_time") * 3600;
426 int duration = get_int_field("General.CheckAuths.duration") * 60;
427 int now = getCurrentSecondsOfDay();
428 if(now < check_start_time && check_start_time+duration >= 86400) {
429 check_start_time -= 86400;
431 if(now >= check_start_time && now < (check_start_time + duration)) {
432 next_call = get_int_field("General.CheckAuths.interval");
433 //get the "longest-unchecked-user"
437 time_t unixtime = time(0);
438 int min_unckecked = get_int_field("General.CheckAuths.min_unckecked");
439 printf_mysql_query("SELECT `user_user`, `user_lastcheck` FROM `users` ORDER BY `user_lastcheck` ASC LIMIT 1");
441 if ((row = mysql_fetch_row(res)) != NULL) {
442 lastcheck = atoi(row[1]);
443 if(!lastcheck || unixtime - lastcheck >= min_unckecked) {
444 lookup_authname(row[0], main_checkauths_callback, NULL);
450 if(now > check_start_time)
451 pending = 86400 - now + check_start_time;
453 pending = check_start_time - now;
459 timeq_add(next_call, main_checkauths, NULL);
462 TIMEQ_CALLBACK(main_statistics) {
463 int update_minutes = get_int_field("statistics.frequency");
464 if(!update_minutes) update_minutes = 2;
465 timeq_add(update_minutes * 60, main_statistics, NULL);
466 if(get_int_field("statistics.enable")) {
467 statistics_enabled = 1;
468 statistics_requested_lusers = 1;
469 if(get_int_field("statistics.include_lusers")) {
470 struct ClientSocket *bot, *lusersbot = NULL;
471 for(bot = getBots(SOCKET_FLAG_READY, NULL); bot; bot = getBots(SOCKET_FLAG_READY, bot)) {
472 if(bot->flags & SOCKET_FLAG_PREFERRED)
476 if(bot == NULL) bot = getBots(SOCKET_FLAG_READY, NULL);
477 putsock(bot, "LUSERS");
482 statistics_enabled = 0;
485 void statistics_update() {
486 if(get_int_field("statistics.enable") && statistics_requested_lusers && get_string_field("statistics.execute")) {
487 statistics_requested_lusers = 0;
488 char command[MAXLEN];
494 - commands per minute
498 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);
499 statistics_privmsg = 0;
500 statistics_commands = 0;
505 void write_log(int loglevel, const char *line, int len) {
506 SYNCHRONIZE(log_sync);
507 if(!daemonized && (print_loglevel & loglevel)) {
509 } else if(!daemonized && loglevel == LOGLEVEL_ERROR) {
510 fprintf(stderr, "%s", line);
512 if(get_int_field("log.loglevel") & loglevel) {
514 log_fptr = fopen(LOG_FILE, "a");
515 if(!log_fptr) goto write_log_end;
520 timeinfo = localtime(&rawtime);
522 int timepos = strftime(timestr, 20, "%x %X ", timeinfo);
523 fwrite(timestr, 1, timepos, log_fptr);
524 fwrite(line, 1, len, log_fptr);
527 DESYNCHRONIZE(log_sync);
530 void putlog(int loglevel, const char *text, ...) {
532 char logBuf[MAXLOGLEN];
535 va_start(arg_list, text);
536 pos = vsnprintf(logBuf, MAXLOGLEN - 1, text, arg_list);
538 if (pos < 0 || pos > (MAXLOGLEN - 1)) pos = MAXLOGLEN - 1;
540 write_log(loglevel, logBuf, pos);
543 static void check_firstrun() {
546 printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_access` = 1000 LIMIT 1");
548 if (mysql_fetch_row(res) == NULL) {
550 printf("No superuser found...\n");
551 check_firstrun_admin:
552 printf("AuthServ account name of admin user: ");
555 fgets(adminuser, 30, stdin);
556 for(ptr = adminuser; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
557 if(strlen(adminuser) < 2) goto check_firstrun_admin;
558 printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_user` = '%s'", escape_string(adminuser));
560 if ((row = mysql_fetch_row(res)) != NULL)
561 printf_mysql_query("UPDATE `users` SET `user_access` = 1000 WHERE `user_id` = '%s'", row[0]);
563 printf_mysql_query("INSERT INTO `users` (`user_user`, `user_access`) VALUES ('%s', 1000)", escape_string(adminuser));
565 printf_mysql_query("SELECT `id` FROM `bots` WHERE `active` = 1 LIMIT 1");
567 if (mysql_fetch_row(res) == NULL) {
569 printf("No active bot found...\n\n");
570 printf("ADD NEW BOT\n");
573 check_firstrun_bot_nick:
575 fgets(bot_nick, 30, stdin);
576 for(ptr = bot_nick; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
577 if(strlen(bot_nick) < 2) goto check_firstrun_bot_nick;
579 check_firstrun_bot_ident:
581 fgets(bot_ident, 15, stdin);
582 for(ptr = bot_ident; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
583 if(strlen(bot_ident) < 2) goto check_firstrun_bot_ident;
584 char bot_realname[101];
585 check_firstrun_bot_realname:
586 printf("Realname: ");
587 fgets(bot_realname, 100, stdin);
588 for(ptr = bot_realname; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
589 if(strlen(bot_realname) < 2) goto check_firstrun_bot_realname;
590 char bot_server[101];
591 check_firstrun_bot_server:
592 printf("Server: [irc.onlinegamesnet.net] ");
593 fgets(bot_server, 100, stdin);
594 for(ptr = bot_server; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
595 if(*bot_server && strlen(bot_nick) < 5) goto check_firstrun_bot_server;
597 strcpy(bot_server, "irc.onlinegamesnet.net");
599 char bot_port_buf[7];
600 printf("Port: [6667] ");
601 fgets(bot_port_buf, 6, stdin);
602 for(ptr = bot_port_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
606 bot_port = atoi(bot_port_buf);
609 check_firstrun_bot_ssl:
610 printf("SSL: [y/N] ");
611 fgets(bot_ssl_buf, 4, stdin);
612 for(ptr = bot_ssl_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
613 if(!*bot_ssl_buf || tolower(*bot_ssl_buf) == 'n')
615 else if(tolower(*bot_ssl_buf) == 'y')
618 goto check_firstrun_bot_ssl;
620 printf("Server Password: [] ");
621 fgets(bot_pass, 100, stdin);
622 for(ptr = bot_pass; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
624 char bot_maxchan_buf[5];
625 printf("MaxChannel: [20] ");
626 fgets(bot_maxchan_buf, 5, stdin);
627 for(ptr = bot_maxchan_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
629 bot_maxchan = atoi(bot_maxchan_buf);
633 char bot_queue_buf[5];
634 check_firstrun_bot_queue:
635 printf("Queue (prevents excess floods): [Y/n] ");
636 fgets(bot_queue_buf, 4, stdin);
637 for(ptr = bot_queue_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
638 if(!*bot_queue_buf || tolower(*bot_queue_buf) == 'y')
640 else if(tolower(*bot_queue_buf) == 'n')
643 goto check_firstrun_bot_queue;
644 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);