6486d6cb3a3de881feff95cf39823cfc4412a8a8
[NeonServV5.git] / src / main.c
1 /* main.c - NeonServ v5.3
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 #include "main.h"
19 #include "signal.h"
20 #include "ClientSocket.h"
21 #include "UserNode.h"
22 #include "ChanNode.h"
23 #include "IRCEvents.h"
24 #include "IRCParser.h"
25 #include "modcmd.h"
26 #include "WHOHandler.h"
27 #include "bots.h"
28 #include "mysqlConn.h"
29 #include "HandleInfoHandler.h"
30 #include "lang.h"
31 #include "tools.h"
32 #include "timeq.h"
33 #include "EventLogger.h"
34 #include "ModeNode.h"
35 #include "IRCQueue.h"
36 #include "DBHelper.h"
37 #include "commands.h"
38 #include "ConfigParser.h"
39 #include "ssl.h"
40 #include "QServer.h"
41 #include "version.h"
42
43 time_t start_time;
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;
54 #ifdef HAVE_THREADS
55 int running_threads;
56 pthread_mutex_t cache_sync;
57 pthread_mutex_t whohandler_sync, whohandler_mass_sync;
58 static pthread_mutex_t log_sync;
59 #endif
60
61 void cleanup() {
62     free_sockets();
63     qserver_free();
64     free_parser();
65     free_UserNode();
66     free_ChanNode();
67     free_bind();
68     free_modcmd();
69     free_whoqueue();
70     free_bots();
71     free_mysql();
72     free_handleinfohandler();
73     free_lang();
74 }
75
76 static int load_mysql_config() {
77     char *mysql_host, *mysql_user, *mysql_pass, *mysql_base;
78     int mysql_serverport;
79     
80     mysql_host = get_string_field("MySQL.host");
81     if(!mysql_host) {
82         perror("invalid neonserv.conf: missing MySQL.host");
83         return 0;
84     }
85     mysql_serverport = get_int_field("MySQL.port");
86     if(!mysql_serverport)
87         mysql_serverport = 3306;
88     mysql_user = get_string_field("MySQL.user");
89     if(!mysql_user) {
90         perror("invalid neonserv.conf: missing MySQL.user");
91         return 0;
92     }
93     mysql_pass = get_string_field("MySQL.pass");
94     if(!mysql_pass) {
95         perror("invalid neonserv.conf: missing MySQL.pass");
96         return 0;
97     }
98     mysql_base = get_string_field("MySQL.base");
99     if(!mysql_base) {
100         perror("invalid neonserv.conf: missing MySQL base");
101         return 0;
102     }
103     init_mysql(mysql_host, mysql_serverport, mysql_user, mysql_pass, mysql_base);
104     return 1;
105 }
106
107 #ifdef HAVE_THREADS
108 pthread_t *current_threads = NULL;
109
110 void * thread_main(void *arg) {
111     time_t socket_wait;
112     while(running) {
113         socket_wait = time(0) + SOCKET_SELECT_TIME;
114         do {
115             socket_loop(SOCKET_SELECT_TIME);
116         } while(time(0) < socket_wait);
117         clearTempUsers();
118         destroyEvents();
119         mysql_free();
120     }
121     running_threads--;
122     return NULL;
123 }
124
125 int getCurrentThreadID() {
126     if(!current_threads) return 0;
127     int i;
128     unsigned int my_tid = (unsigned int) pthread_self_tid();
129     for(i = 0; i < running_threads; i++) {
130         #ifdef WIN32
131         if((unsigned int) current_threads[i].p == my_tid)
132         #else
133         if((unsigned int) current_threads[i] == my_tid)
134         #endif
135             return i+1;
136     }
137     return 0;
138 }
139
140 #endif
141
142 void exit_daemon() {
143     if(daemonized) {
144         remove(PID_FILE);
145     }
146 }
147
148 int main(int argc, char *argv[]) {
149     int run_as_daemon = 1;
150     int argi;
151     process_argv = argv;
152     process_argc = argc;
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")) {
156             run_as_daemon = 0;
157         } else if(!strcmp(argv[argi], "-s") || !strcmp(argv[argi], "--show")) {
158             if(argi+1 == argc) break;
159             argi++;
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);
164             exit(0);
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");
171             exit(0);
172         }
173     }
174     if(geteuid() == 0 || getuid() == 0) {
175         fprintf(stderr, "NeonServ may not be run with super user privileges.\n");
176         exit(0);
177     }
178     if(!loadConfig(CONF_FILE)) {
179         fprintf(stderr, "Unable to load " CONF_FILE "\n");
180         exit(0);
181     }
182     #if HAVE_THREADS
183     THREAD_MUTEX_INIT(log_sync);
184     #endif
185     if (run_as_daemon) {
186         /* Attempt to fork into the background if daemon mode is on. */
187         pid_t pid = fork();
188         if (pid < 0) {
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);
193             exit(0);
194         }
195         setsid();
196         daemonized = 1;
197         atexit(exit_daemon);
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));
202         } else {
203             fprintf(pidfile, "%i\n", (int)getpid());
204             fclose(pidfile);
205         }
206         fclose(stdin);
207         fclose(stdout);
208         fclose(stderr);
209     }
210     
211 main:
212     signal(SIGABRT, sighandler);
213     signal(SIGFPE, sighandler);
214     signal(SIGILL, sighandler);
215     signal(SIGINT, sighandler);
216     signal(SIGSEGV, sighandler);
217     signal(SIGTERM, sighandler);
218     
219     #ifdef ENABLE_MEMORY_DEBUG
220     initMemoryDebug();
221     #endif
222     
223     start_time = time(0);
224     
225     #ifdef WIN32
226     int res;
227     WSADATA wsadata;
228     // Start Windows Sockets.
229     res = WSAStartup(MAKEWORD(2, 0), &wsadata);
230     if (res)
231     {
232         perror("Unable to start Windows Sockets");
233         return 0;
234     }
235     #endif
236     
237     if(!load_mysql_config()) return 0;
238     
239     statistics_enabled = get_int_field("statistics.enable");
240     
241     #ifdef HAVE_THREADS
242     THREAD_MUTEX_INIT(cache_sync);
243     THREAD_MUTEX_INIT(whohandler_sync);
244     THREAD_MUTEX_INIT(whohandler_mass_sync);
245     #endif
246     
247     queue_init();
248     init_sockets();
249     init_timeq();
250     init_lang();
251     ssl_init();
252     init_parser();
253     init_UserNode();
254     init_ChanNode();
255     init_ModeNode();
256     init_bind();
257         init_modcmd();
258     init_handleinfohandler();
259     init_tools();
260     register_commands();
261     init_bots();
262     init_DBHelper();
263     qserver_init();
264     
265     load_languages();
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);
269     
270     timeq_add(90, main_checkauths, NULL);
271     
272     int worker_threads = get_int_field("General.worker_threads");
273     if(!worker_threads) worker_threads = 1;
274     running = 1;
275     #ifdef HAVE_THREADS
276     int tid_id = 0;
277     current_threads = calloc(worker_threads, sizeof(*current_threads));
278     for(tid_id = 0; tid_id < worker_threads; tid_id++) {
279         running_threads++;
280         pthread_create(&current_threads[tid_id], NULL, thread_main, NULL);
281     }
282     int usleep_delay = 1000000 / TICKS_PER_SECOND;
283     while(running) {
284         timeq_tick();
285         loop_bots();
286         qserver_loop();
287         queue_loop();
288         mysql_free();
289         usleep(usleep_delay);
290     }
291     for(tid_id = 0; tid_id < worker_threads; tid_id++) {
292         pthread_join(current_threads[tid_id], NULL);
293     }
294     running_threads = 0;
295     #else
296     time_t socket_wait;
297     while(running) {
298         socket_wait = time(0) + SOCKET_SELECT_TIME;
299         do {
300             socket_loop(SOCKET_SELECT_TIME);
301         } while(time(0) < socket_wait);
302         timeq_tick();
303         loop_bots();
304         clearTempUsers();
305         destroyEvents();
306         qserver_loop();
307         queue_loop();
308         mysql_free();
309     }
310     #endif
311     cleanup();
312     if(hard_restart) {
313         restart_process();
314     }
315     goto main;
316 }
317
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;
323     #ifdef WIN32
324     execv(process_argv[0], (const char * const*)restart_argv);
325     #else
326     execv(process_argv[0], restart_argv);
327     #endif
328 }
329
330 int stricmp (const char *s1, const char *s2)
331 {
332    if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
333    if (s2 == NULL) return *s1;
334    char c1, c2;
335    while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
336    {
337      if (*s1 == '\0') break;
338      ++s1; ++s2;
339    }
340    return c1 - c2;
341 }
342
343 int stricmplen (const char *s1, const char *s2, int len)
344 {
345    if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
346    if (s2 == NULL) return *s1;
347    char c1, c2;
348    int i = 0;
349    while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
350    {
351      i++;
352      if (*s1 == '\0') break;
353      ++s1; ++s2;
354      if(i == len) break;
355    }
356    return c1 - c2;
357 }
358
359 void restart_bot(int do_hard_restart) {
360     hard_restart = do_hard_restart;
361     running = 0;
362 }
363
364 void stop_bot() {
365     cleanup();
366     exit(0);
367 }
368
369 void reload_config() {
370     loadConfig(CONF_FILE);
371 }
372
373 static int getCurrentSecondsOfDay() {
374     time_t now = time(0);
375     struct tm *timeofday = localtime(&now);
376     int seconds = 0;
377     seconds += timeofday->tm_hour * 3600;
378     seconds += timeofday->tm_min * 60;
379     seconds += timeofday->tm_sec;
380     return seconds;
381 }
382
383 static AUTHLOOKUP_CALLBACK(main_checkauths_callback) {
384     //check if registered is still valid
385     MYSQL_RES *res;
386     MYSQL_ROW row;
387     printf_mysql_query("SELECT `user_id`, `user_registered` FROM `users` WHERE `user_user` = '%s'", escape_string(auth));
388     res = mysql_use();
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");
394             if(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);
399                 }
400             }
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]);
403         } else {
404             printf_mysql_query("UPDATE `users` SET `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", row[0]);
405         }
406     }
407 }
408
409 TIMEQ_CALLBACK(main_checkauths) {
410     int next_call = 600;
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;
417         }
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"
421             MYSQL_RES *res;
422             MYSQL_ROW row;
423             int lastcheck;
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");
427             res = mysql_use();
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);
432                 } else 
433                     next_call = 300;
434             }
435         } else {
436             int pending;
437             if(now > check_start_time)
438                 pending = 86400 - now + check_start_time;
439             else
440                 pending = check_start_time - now;
441             if(pending < 600)
442                 next_call = pending;
443         }
444         
445     }
446     timeq_add(next_call, main_checkauths, NULL);
447 }
448
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)
460                     lusersbot = bot;
461             }
462             bot = lusersbot;
463             if(bot == NULL) bot = getBots(SOCKET_FLAG_READY, NULL);
464             putsock(bot, "LUSERS");
465         } else {
466             statistics_update();
467         }
468     } else
469         statistics_enabled = 0;
470 }
471
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];
476         /* parameters:
477          - visible users
478          - visible chanusers
479          - visible channels
480          - privmsg per minute
481          - commands per minute
482          - network users
483          - network channels
484         */
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;
488         system(command);
489     }
490 }
491
492 void write_log(int loglevel, const char *line, int len) {
493     SYNCHRONIZE(log_sync);
494     if(!daemonized && (print_loglevel & loglevel)) {
495         printf("%s", line);
496     } else if(!daemonized && loglevel == LOGLEVEL_ERROR) {
497         fprintf(stderr, "%s", line);
498     }
499     if(get_int_field("log.loglevel") & loglevel) {
500         if(!log_fptr) {
501             log_fptr = fopen(LOG_FILE, "a");
502             if(!log_fptr) goto write_log_end;
503         }
504         time_t rawtime;
505         struct tm *timeinfo;
506         time(&rawtime);
507         timeinfo = localtime(&rawtime);
508         char timestr[20];
509         int timepos = strftime(timestr, 20, "%x %X ", timeinfo);
510         fwrite(timestr, 1, timepos, log_fptr);
511         fwrite(line, 1, len, log_fptr);
512     }
513     write_log_end:
514     DESYNCHRONIZE(log_sync);
515 }
516
517 void putlog(int loglevel, const char *text, ...) {
518     va_list arg_list;
519     char logBuf[MAXLOGLEN];
520     int pos;
521     logBuf[0] = '\0';
522     va_start(arg_list, text);
523     pos = vsnprintf(logBuf, MAXLOGLEN - 1, text, arg_list);
524     va_end(arg_list);
525     if (pos < 0 || pos > (MAXLOGLEN - 1)) pos = MAXLOGLEN - 1;
526     logBuf[pos] = '\0';
527     write_log(loglevel, logBuf, pos);
528 }
529