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;
72 free_handleinfohandler();
76 static int load_mysql_config() {
77 char *mysql_host, *mysql_user, *mysql_pass, *mysql_base;
80 mysql_host = get_string_field("MySQL.host");
82 perror("invalid neonserv.conf: missing MySQL.host");
85 mysql_serverport = get_int_field("MySQL.port");
87 mysql_serverport = 3306;
88 mysql_user = get_string_field("MySQL.user");
90 perror("invalid neonserv.conf: missing MySQL.user");
93 mysql_pass = get_string_field("MySQL.pass");
95 perror("invalid neonserv.conf: missing MySQL.pass");
98 mysql_base = get_string_field("MySQL.base");
100 perror("invalid neonserv.conf: missing MySQL base");
103 init_mysql(mysql_host, mysql_serverport, mysql_user, mysql_pass, mysql_base);
108 pthread_t *current_threads = NULL;
110 void * thread_main(void *arg) {
113 socket_wait = time(0) + SOCKET_SELECT_TIME;
115 socket_loop(SOCKET_SELECT_TIME);
116 } while(time(0) < socket_wait);
124 int getCurrentThreadID() {
125 if(!current_threads) return 0;
127 unsigned int my_tid = (unsigned int) pthread_self_tid();
128 for(i = 0; i < running_threads; i++) {
130 if((unsigned int) current_threads[i].p == my_tid)
132 if((unsigned int) current_threads[i] == my_tid)
147 int main(int argc, char *argv[]) {
148 int run_as_daemon = 1;
152 printf("NeonServ v%s\n\n", NEONSERV_VERSION);
153 for(argi = 1; argi < argc; argi++) {
154 if(!strcmp(argv[argi], "-f") || !strcmp(argv[argi], "--foreground")) {
156 } else if(!strcmp(argv[argi], "-s") || !strcmp(argv[argi], "--show")) {
157 if(argi+1 == argc) break;
159 print_loglevel = atoi(argv[argi]);
160 } else if(!strcmp(argv[argi], "-v") || !strcmp(argv[argi], "--version")) {
161 printf("Version: %s.%d (%s)\n", NEONSERV_VERSION, patchlevel, (strcmp(revision, "") ? revision : "-"));
162 printf("Build: #%s %s (%s lines, " COMPILER ")\n", compilation, creation, codelines);
164 } else if(!strcmp(argv[argi], "-h") || !strcmp(argv[argi], "--help")) {
165 printf("Usage: ./neonserv [-s loglevel] [-f] [-h|-v]\n");
166 printf(" -s, --show show log lines matching loglevel in stdout.\n");
167 printf(" -f, --foreground run NeonServ in the foreground.\n");
168 printf(" -h, --help prints this usage message.\n");
169 printf(" -v, --version prints this program's version.\n");
173 if(geteuid() == 0 || getuid() == 0) {
174 fprintf(stderr, "NeonServ may not be run with super user privileges.\n");
177 if(!loadConfig(CONF_FILE)) {
178 fprintf(stderr, "Unable to load " CONF_FILE "\n");
182 THREAD_MUTEX_INIT(log_sync);
185 /* Attempt to fork into the background if daemon mode is on. */
188 fprintf(stderr, "Unable to fork: %s\n", strerror(errno));
189 } else if (pid > 0) {
190 printf("Forking into the background (pid: %d)...\n", pid);
191 putlog(LOGLEVEL_INFO, "Forking into the background (pid: %d)...\n", pid);
197 FILE *pidfile = fopen(PID_FILE, "w");
198 if (pidfile == NULL) {
199 fprintf(stderr, "Unable to create PID file: %s", strerror(errno));
200 putlog(LOGLEVEL_ERROR, "Unable to create PID file: %s", strerror(errno));
202 fprintf(pidfile, "%i\n", (int)getpid());
211 signal(SIGABRT, sighandler);
212 signal(SIGFPE, sighandler);
213 signal(SIGILL, sighandler);
214 signal(SIGINT, sighandler);
215 signal(SIGSEGV, sighandler);
216 signal(SIGTERM, sighandler);
218 #ifdef ENABLE_MEMORY_DEBUG
222 start_time = time(0);
227 // Start Windows Sockets.
228 res = WSAStartup(MAKEWORD(2, 0), &wsadata);
231 perror("Unable to start Windows Sockets");
236 if(!load_mysql_config()) return 0;
238 statistics_enabled = get_int_field("statistics.enable");
241 THREAD_MUTEX_INIT(cache_sync);
242 THREAD_MUTEX_INIT(whohandler_sync);
243 THREAD_MUTEX_INIT(whohandler_mass_sync);
257 init_handleinfohandler();
265 int update_minutes = get_int_field("statistics.frequency");
266 if(!update_minutes) update_minutes = 2;
267 timeq_add(update_minutes * 60 + 10, main_statistics, NULL);
269 timeq_add(90, main_checkauths, NULL);
271 int worker_threads = get_int_field("General.worker_threads");
272 if(!worker_threads) worker_threads = 1;
276 current_threads = calloc(worker_threads, sizeof(*current_threads));
277 for(tid_id = 0; tid_id < worker_threads; tid_id++) {
279 pthread_create(¤t_threads[tid_id], NULL, thread_main, NULL);
281 int usleep_delay = 1000000 / TICKS_PER_SECOND;
287 usleep(usleep_delay);
289 for(tid_id = 0; tid_id < worker_threads; tid_id++) {
290 pthread_join(current_threads[tid_id], NULL);
296 socket_wait = time(0) + SOCKET_SELECT_TIME;
298 socket_loop(SOCKET_SELECT_TIME);
299 } while(time(0) < socket_wait);
315 void restart_process() {
316 /* Append a NULL to the end of argv[]. */
317 char **restart_argv = (char **)alloca((process_argc + 1) * sizeof(char *));
318 memcpy(restart_argv, process_argv, process_argc * sizeof(char *));
319 restart_argv[process_argc] = NULL;
321 execv(process_argv[0], (const char * const*)restart_argv);
323 execv(process_argv[0], restart_argv);
327 int stricmp (const char *s1, const char *s2)
329 if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
330 if (s2 == NULL) return *s1;
332 while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
334 if (*s1 == '\0') break;
340 int stricmplen (const char *s1, const char *s2, int len)
342 if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
343 if (s2 == NULL) return *s1;
346 while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
349 if (*s1 == '\0') break;
356 void restart_bot(int do_hard_restart) {
357 hard_restart = do_hard_restart;
366 void reload_config() {
367 loadConfig(CONF_FILE);
370 static int getCurrentSecondsOfDay() {
371 time_t now = time(0);
372 struct tm *timeofday = localtime(&now);
374 seconds += timeofday->tm_hour * 3600;
375 seconds += timeofday->tm_min * 60;
376 seconds += timeofday->tm_sec;
380 static AUTHLOOKUP_CALLBACK(main_checkauths_callback) {
381 //check if registered is still valid
384 printf_mysql_query("SELECT `user_id`, `user_registered` FROM `users` WHERE `user_user` = '%s'", escape_string(auth));
386 if ((row = mysql_fetch_row(res)) != NULL) {
387 if(!exists || (strcmp(row[1], "0") && registered != atoi(row[1]))) {
388 //User is no longer valid! Delete it...
389 deleteUser(atoi(row[0]));
390 char *alertchan = get_string_field("General.CheckAuths.alertchan");
392 struct ChanNode *alertchan_chan = getChanByName(alertchan);
393 struct ClientSocket *alertclient;
394 if(alertchan_chan && (alertclient = getChannelBot(alertchan_chan, 0)) != NULL) {
395 putsock(alertclient, "PRIVMSG %s :Deleted User %s", alertchan_chan->name, auth);
398 } else if(exists && !strcmp(row[1], "0")) {
399 printf_mysql_query("UPDATE `users` SET `user_registered` = '%lu', `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", (unsigned long) registered, row[0]);
401 printf_mysql_query("UPDATE `users` SET `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", row[0]);
406 TIMEQ_CALLBACK(main_checkauths) {
408 if(get_int_field("General.CheckAuths.enabled")) {
409 int check_start_time = get_int_field("General.CheckAuths.start_time") * 3600;
410 int duration = get_int_field("General.CheckAuths.duration") * 60;
411 int now = getCurrentSecondsOfDay();
412 if(now < check_start_time && check_start_time+duration >= 86400) {
413 check_start_time -= 86400;
415 if(now >= check_start_time && now < (check_start_time + duration)) {
416 next_call = get_int_field("General.CheckAuths.interval");
417 //get the "longest-unchecked-user"
421 time_t unixtime = time(0);
422 int min_unckecked = get_int_field("General.CheckAuths.min_unckecked");
423 printf_mysql_query("SELECT `user_user`, `user_lastcheck` FROM `users` ORDER BY `user_lastcheck` ASC LIMIT 1");
425 if ((row = mysql_fetch_row(res)) != NULL) {
426 lastcheck = atoi(row[1]);
427 if(!lastcheck || unixtime - lastcheck >= min_unckecked) {
428 lookup_authname(row[0], main_checkauths_callback, NULL);
434 if(now > check_start_time)
435 pending = 86400 - now + check_start_time;
437 pending = check_start_time - now;
443 timeq_add(next_call, main_checkauths, NULL);
446 TIMEQ_CALLBACK(main_statistics) {
447 int update_minutes = get_int_field("statistics.frequency");
448 if(!update_minutes) update_minutes = 2;
449 timeq_add(update_minutes * 60, main_statistics, NULL);
450 if(get_int_field("statistics.enable")) {
451 statistics_enabled = 1;
452 statistics_requested_lusers = 1;
453 if(get_int_field("statistics.include_lusers")) {
454 struct ClientSocket *bot, *lusersbot = NULL;
455 for(bot = getBots(SOCKET_FLAG_READY, NULL); bot; bot = getBots(SOCKET_FLAG_READY, bot)) {
456 if(bot->flags & SOCKET_FLAG_PREFERRED)
460 if(bot == NULL) bot = getBots(SOCKET_FLAG_READY, NULL);
461 putsock(bot, "LUSERS");
466 statistics_enabled = 0;
469 void statistics_update() {
470 if(get_int_field("statistics.enable") && statistics_requested_lusers && get_string_field("statistics.execute")) {
471 statistics_requested_lusers = 0;
472 char command[MAXLEN];
478 - commands per minute
482 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);
483 statistics_privmsg = 0;
484 statistics_commands = 0;
489 void write_log(int loglevel, const char *line, int len) {
490 SYNCHRONIZE(log_sync);
491 if(!daemonized && (print_loglevel & loglevel)) {
493 } else if(!daemonized && loglevel == LOGLEVEL_ERROR) {
494 fprintf(stderr, "%s", line);
496 if(get_int_field("log.loglevel") & loglevel) {
498 log_fptr = fopen(LOG_FILE, "a");
499 if(!log_fptr) goto write_log_end;
504 timeinfo = localtime(&rawtime);
506 int timepos = strftime(timestr, 20, "%x %X ", timeinfo);
507 fwrite(timestr, 1, timepos, log_fptr);
508 fwrite(line, 1, len, log_fptr);
511 DESYNCHRONIZE(log_sync);
514 void putlog(int loglevel, const char *text, ...) {
516 char logBuf[MAXLOGLEN];
519 va_start(arg_list, text);
520 pos = vsnprintf(logBuf, MAXLOGLEN - 1, text, arg_list);
522 if (pos < 0 || pos > (MAXLOGLEN - 1)) pos = MAXLOGLEN - 1;
524 write_log(loglevel, logBuf, pos);