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);
125 int getCurrentThreadID() {
126 if(!current_threads) return 0;
128 unsigned int my_tid = (unsigned int) pthread_self_tid();
129 for(i = 0; i < running_threads; i++) {
131 if((unsigned int) current_threads[i].p == my_tid)
133 if((unsigned int) current_threads[i] == my_tid)
148 int main(int argc, char *argv[]) {
149 int run_as_daemon = 1;
153 printf("NeonServ v%s\n\n", NEONSERV_VERSION);
154 for(argi = 1; argi < argc; argi++) {
155 if(!strcmp(argv[argi], "-f") || !strcmp(argv[argi], "--foreground")) {
157 } else if(!strcmp(argv[argi], "-s") || !strcmp(argv[argi], "--show")) {
158 if(argi+1 == argc) break;
160 print_loglevel = atoi(argv[argi]);
161 } else if(!strcmp(argv[argi], "-v") || !strcmp(argv[argi], "--version")) {
162 printf("Version: %s.%d (%s)\n", NEONSERV_VERSION, patchlevel, (strcmp(revision, "") ? revision : "-"));
163 printf("Build: #%s %s (%s lines, " COMPILER ")\n", compilation, creation, codelines);
165 } else if(!strcmp(argv[argi], "-h") || !strcmp(argv[argi], "--help")) {
166 printf("Usage: ./neonserv [-s loglevel] [-f] [-h|-v]\n");
167 printf(" -s, --show show log lines matching loglevel in stdout.\n");
168 printf(" -f, --foreground run NeonServ in the foreground.\n");
169 printf(" -h, --help prints this usage message.\n");
170 printf(" -v, --version prints this program's version.\n");
174 if(geteuid() == 0 || getuid() == 0) {
175 fprintf(stderr, "NeonServ may not be run with super user privileges.\n");
178 if(!loadConfig(CONF_FILE)) {
179 fprintf(stderr, "Unable to load " CONF_FILE "\n");
183 THREAD_MUTEX_INIT(log_sync);
186 /* Attempt to fork into the background if daemon mode is on. */
189 fprintf(stderr, "Unable to fork: %s\n", strerror(errno));
190 } else if (pid > 0) {
191 printf("Forking into the background (pid: %d)...\n", pid);
192 putlog(LOGLEVEL_INFO, "Forking into the background (pid: %d)...\n", pid);
198 FILE *pidfile = fopen(PID_FILE, "w");
199 if (pidfile == NULL) {
200 fprintf(stderr, "Unable to create PID file: %s", strerror(errno));
201 putlog(LOGLEVEL_ERROR, "Unable to create PID file: %s", strerror(errno));
203 fprintf(pidfile, "%i\n", (int)getpid());
212 signal(SIGABRT, sighandler);
213 signal(SIGFPE, sighandler);
214 signal(SIGILL, sighandler);
215 signal(SIGINT, sighandler);
216 signal(SIGSEGV, sighandler);
217 signal(SIGTERM, sighandler);
219 #ifdef ENABLE_MEMORY_DEBUG
223 start_time = time(0);
228 // Start Windows Sockets.
229 res = WSAStartup(MAKEWORD(2, 0), &wsadata);
232 perror("Unable to start Windows Sockets");
237 if(!load_mysql_config()) return 0;
239 statistics_enabled = get_int_field("statistics.enable");
242 THREAD_MUTEX_INIT(cache_sync);
243 THREAD_MUTEX_INIT(whohandler_sync);
244 THREAD_MUTEX_INIT(whohandler_mass_sync);
258 init_handleinfohandler();
266 int update_minutes = get_int_field("statistics.frequency");
267 if(!update_minutes) update_minutes = 2;
268 timeq_add(update_minutes * 60 + 10, main_statistics, NULL);
270 timeq_add(90, main_checkauths, NULL);
272 int worker_threads = get_int_field("General.worker_threads");
273 if(!worker_threads) worker_threads = 1;
277 current_threads = calloc(worker_threads, sizeof(*current_threads));
278 for(tid_id = 0; tid_id < worker_threads; tid_id++) {
280 pthread_create(¤t_threads[tid_id], NULL, thread_main, NULL);
282 int usleep_delay = 1000000 / TICKS_PER_SECOND;
289 usleep(usleep_delay);
291 for(tid_id = 0; tid_id < worker_threads; tid_id++) {
292 pthread_join(current_threads[tid_id], NULL);
298 socket_wait = time(0) + SOCKET_SELECT_TIME;
300 socket_loop(SOCKET_SELECT_TIME);
301 } while(time(0) < socket_wait);
318 void restart_process() {
319 /* Append a NULL to the end of argv[]. */
320 char **restart_argv = (char **)alloca((process_argc + 1) * sizeof(char *));
321 memcpy(restart_argv, process_argv, process_argc * sizeof(char *));
322 restart_argv[process_argc] = NULL;
324 execv(process_argv[0], (const char * const*)restart_argv);
326 execv(process_argv[0], restart_argv);
330 int stricmp (const char *s1, const char *s2)
332 if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
333 if (s2 == NULL) return *s1;
335 while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
337 if (*s1 == '\0') break;
343 int stricmplen (const char *s1, const char *s2, int len)
345 if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
346 if (s2 == NULL) return *s1;
349 while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
352 if (*s1 == '\0') break;
359 void restart_bot(int do_hard_restart) {
360 hard_restart = do_hard_restart;
369 void reload_config() {
370 loadConfig(CONF_FILE);
373 static int getCurrentSecondsOfDay() {
374 time_t now = time(0);
375 struct tm *timeofday = localtime(&now);
377 seconds += timeofday->tm_hour * 3600;
378 seconds += timeofday->tm_min * 60;
379 seconds += timeofday->tm_sec;
383 static AUTHLOOKUP_CALLBACK(main_checkauths_callback) {
384 //check if registered is still valid
387 printf_mysql_query("SELECT `user_id`, `user_registered` FROM `users` WHERE `user_user` = '%s'", escape_string(auth));
389 if ((row = mysql_fetch_row(res)) != NULL) {
390 if(!exists || (strcmp(row[1], "0") && registered != atoi(row[1]))) {
391 //User is no longer valid! Delete it...
392 deleteUser(atoi(row[0]));
393 char *alertchan = get_string_field("General.CheckAuths.alertchan");
395 struct ChanNode *alertchan_chan = getChanByName(alertchan);
396 struct ClientSocket *alertclient;
397 if(alertchan_chan && (alertclient = getChannelBot(alertchan_chan, 0)) != NULL) {
398 putsock(alertclient, "PRIVMSG %s :Deleted User %s", alertchan_chan->name, auth);
401 } else if(exists && !strcmp(row[1], "0")) {
402 printf_mysql_query("UPDATE `users` SET `user_registered` = '%lu', `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", (unsigned long) registered, row[0]);
404 printf_mysql_query("UPDATE `users` SET `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", row[0]);
409 TIMEQ_CALLBACK(main_checkauths) {
411 if(get_int_field("General.CheckAuths.enabled")) {
412 int check_start_time = get_int_field("General.CheckAuths.start_time") * 3600;
413 int duration = get_int_field("General.CheckAuths.duration") * 60;
414 int now = getCurrentSecondsOfDay();
415 if(now < check_start_time && check_start_time+duration >= 86400) {
416 check_start_time -= 86400;
418 if(now >= check_start_time && now < (check_start_time + duration)) {
419 next_call = get_int_field("General.CheckAuths.interval");
420 //get the "longest-unchecked-user"
424 time_t unixtime = time(0);
425 int min_unckecked = get_int_field("General.CheckAuths.min_unckecked");
426 printf_mysql_query("SELECT `user_user`, `user_lastcheck` FROM `users` ORDER BY `user_lastcheck` ASC LIMIT 1");
428 if ((row = mysql_fetch_row(res)) != NULL) {
429 lastcheck = atoi(row[1]);
430 if(!lastcheck || unixtime - lastcheck >= min_unckecked) {
431 lookup_authname(row[0], main_checkauths_callback, NULL);
437 if(now > check_start_time)
438 pending = 86400 - now + check_start_time;
440 pending = check_start_time - now;
446 timeq_add(next_call, main_checkauths, NULL);
449 TIMEQ_CALLBACK(main_statistics) {
450 int update_minutes = get_int_field("statistics.frequency");
451 if(!update_minutes) update_minutes = 2;
452 timeq_add(update_minutes * 60, main_statistics, NULL);
453 if(get_int_field("statistics.enable")) {
454 statistics_enabled = 1;
455 statistics_requested_lusers = 1;
456 if(get_int_field("statistics.include_lusers")) {
457 struct ClientSocket *bot, *lusersbot = NULL;
458 for(bot = getBots(SOCKET_FLAG_READY, NULL); bot; bot = getBots(SOCKET_FLAG_READY, bot)) {
459 if(bot->flags & SOCKET_FLAG_PREFERRED)
463 if(bot == NULL) bot = getBots(SOCKET_FLAG_READY, NULL);
464 putsock(bot, "LUSERS");
469 statistics_enabled = 0;
472 void statistics_update() {
473 if(get_int_field("statistics.enable") && statistics_requested_lusers && get_string_field("statistics.execute")) {
474 statistics_requested_lusers = 0;
475 char command[MAXLEN];
481 - commands per minute
485 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);
486 statistics_privmsg = 0;
487 statistics_commands = 0;
492 void write_log(int loglevel, const char *line, int len) {
493 SYNCHRONIZE(log_sync);
494 if(!daemonized && (print_loglevel & loglevel)) {
496 } else if(!daemonized && loglevel == LOGLEVEL_ERROR) {
497 fprintf(stderr, "%s", line);
499 if(get_int_field("log.loglevel") & loglevel) {
501 log_fptr = fopen(LOG_FILE, "a");
502 if(!log_fptr) goto write_log_end;
507 timeinfo = localtime(&rawtime);
509 int timepos = strftime(timestr, 20, "%x %X ", timeinfo);
510 fwrite(timestr, 1, timepos, log_fptr);
511 fwrite(line, 1, len, log_fptr);
514 DESYNCHRONIZE(log_sync);
517 void putlog(int loglevel, const char *text, ...) {
519 char logBuf[MAXLOGLEN];
522 va_start(arg_list, text);
523 pos = vsnprintf(logBuf, MAXLOGLEN - 1, text, arg_list);
525 if (pos < 0 || pos > (MAXLOGLEN - 1)) pos = MAXLOGLEN - 1;
527 write_log(loglevel, logBuf, pos);