moving NeonServ into background by default; added a few startup parameters
[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     }
120     running_threads--;
121     return NULL;
122 }
123
124 int getCurrentThreadID() {
125     if(!current_threads) return 0;
126     int i;
127     unsigned int my_tid = (unsigned int) pthread_self_tid();
128     for(i = 0; i < running_threads; i++) {
129         #ifdef WIN32
130         if((unsigned int) current_threads[i].p == my_tid)
131         #else
132         if((unsigned int) current_threads[i] == my_tid)
133         #endif
134             return i+1;
135     }
136     return 0;
137 }
138
139 #endif
140
141 void exit_daemon() {
142     if(daemonized) {
143         remove(PID_FILE);
144     }
145 }
146
147 int main(int argc, char *argv[]) {
148     int run_as_daemon = 1;
149     int argi;
150     process_argv = argv;
151     process_argc = argc;
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")) {
155             run_as_daemon = 0;
156         } else if(!strcmp(argv[argi], "-s") || !strcmp(argv[argi], "--show")) {
157             if(argi+1 == argc) break;
158             argi++;
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);
163             exit(0);
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");
170             exit(0);
171         }
172     }
173     if(geteuid() == 0 || getuid() == 0) {
174         fprintf(stderr, "NeonServ may not be run with super user privileges.\n");
175         exit(0);
176     }
177     if(!loadConfig(CONF_FILE)) {
178         fprintf(stderr, "Unable to load " CONF_FILE "\n");
179         exit(0);
180     }
181     #if HAVE_THREADS
182     THREAD_MUTEX_INIT(log_sync);
183     #endif
184     if (run_as_daemon) {
185         /* Attempt to fork into the background if daemon mode is on. */
186         pid_t pid = fork();
187         if (pid < 0) {
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);
192             exit(0);
193         }
194         setsid();
195         daemonized = 1;
196         atexit(exit_daemon);
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));
201         } else {
202             fprintf(pidfile, "%i\n", (int)getpid());
203             fclose(pidfile);
204         }
205         fclose(stdin);
206         fclose(stdout);
207         fclose(stderr);
208     }
209     
210 main:
211     signal(SIGABRT, sighandler);
212     signal(SIGFPE, sighandler);
213     signal(SIGILL, sighandler);
214     signal(SIGINT, sighandler);
215     signal(SIGSEGV, sighandler);
216     signal(SIGTERM, sighandler);
217     
218     #ifdef ENABLE_MEMORY_DEBUG
219     initMemoryDebug();
220     #endif
221     
222     start_time = time(0);
223     
224     #ifdef WIN32
225     int res;
226     WSADATA wsadata;
227     // Start Windows Sockets.
228     res = WSAStartup(MAKEWORD(2, 0), &wsadata);
229     if (res)
230     {
231         perror("Unable to start Windows Sockets");
232         return 0;
233     }
234     #endif
235     
236     if(!load_mysql_config()) return 0;
237     
238     statistics_enabled = get_int_field("statistics.enable");
239     
240     #ifdef HAVE_THREADS
241     THREAD_MUTEX_INIT(cache_sync);
242     THREAD_MUTEX_INIT(whohandler_sync);
243     THREAD_MUTEX_INIT(whohandler_mass_sync);
244     #endif
245     
246     queue_init();
247     init_sockets();
248     init_timeq();
249     init_lang();
250     ssl_init();
251     init_parser();
252     init_UserNode();
253     init_ChanNode();
254     init_ModeNode();
255     init_bind();
256         init_modcmd();
257     init_handleinfohandler();
258     init_tools();
259     register_commands();
260     init_bots();
261     init_DBHelper();
262     qserver_init();
263     
264     load_languages();
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);
268     
269     timeq_add(90, main_checkauths, NULL);
270     
271     int worker_threads = get_int_field("General.worker_threads");
272     if(!worker_threads) worker_threads = 1;
273     running = 1;
274     #ifdef HAVE_THREADS
275     int tid_id = 0;
276     current_threads = calloc(worker_threads, sizeof(*current_threads));
277     for(tid_id = 0; tid_id < worker_threads; tid_id++) {
278         running_threads++;
279         pthread_create(&current_threads[tid_id], NULL, thread_main, NULL);
280     }
281     int usleep_delay = 1000000 / TICKS_PER_SECOND;
282     while(running) {
283         timeq_tick();
284         loop_bots();
285         qserver_loop();
286         queue_loop();
287         usleep(usleep_delay);
288     }
289     for(tid_id = 0; tid_id < worker_threads; tid_id++) {
290         pthread_join(current_threads[tid_id], NULL);
291     }
292     running_threads = 0;
293     #else
294     time_t socket_wait;
295     while(running) {
296         socket_wait = time(0) + SOCKET_SELECT_TIME;
297         do {
298             socket_loop(SOCKET_SELECT_TIME);
299         } while(time(0) < socket_wait);
300         timeq_tick();
301         loop_bots();
302         clearTempUsers();
303         destroyEvents();
304         qserver_loop();
305         queue_loop();
306     }
307     #endif
308     cleanup();
309     if(hard_restart) {
310         restart_process();
311     }
312     goto main;
313 }
314
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;
320     #ifdef WIN32
321     execv(process_argv[0], (const char * const*)restart_argv);
322     #else
323     execv(process_argv[0], restart_argv);
324     #endif
325 }
326
327 int stricmp (const char *s1, const char *s2)
328 {
329    if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
330    if (s2 == NULL) return *s1;
331    char c1, c2;
332    while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
333    {
334      if (*s1 == '\0') break;
335      ++s1; ++s2;
336    }
337    return c1 - c2;
338 }
339
340 int stricmplen (const char *s1, const char *s2, int len)
341 {
342    if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
343    if (s2 == NULL) return *s1;
344    char c1, c2;
345    int i = 0;
346    while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
347    {
348      i++;
349      if (*s1 == '\0') break;
350      ++s1; ++s2;
351      if(i == len) break;
352    }
353    return c1 - c2;
354 }
355
356 void restart_bot(int do_hard_restart) {
357     hard_restart = do_hard_restart;
358     running = 0;
359 }
360
361 void stop_bot() {
362     cleanup();
363     exit(0);
364 }
365
366 void reload_config() {
367     loadConfig(CONF_FILE);
368 }
369
370 static int getCurrentSecondsOfDay() {
371     time_t now = time(0);
372     struct tm *timeofday = localtime(&now);
373     int seconds = 0;
374     seconds += timeofday->tm_hour * 3600;
375     seconds += timeofday->tm_min * 60;
376     seconds += timeofday->tm_sec;
377     return seconds;
378 }
379
380 static AUTHLOOKUP_CALLBACK(main_checkauths_callback) {
381     //check if registered is still valid
382     MYSQL_RES *res;
383     MYSQL_ROW row;
384     printf_mysql_query("SELECT `user_id`, `user_registered` FROM `users` WHERE `user_user` = '%s'", escape_string(auth));
385     res = mysql_use();
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");
391             if(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);
396                 }
397             }
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]);
400         } else {
401             printf_mysql_query("UPDATE `users` SET `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", row[0]);
402         }
403     }
404 }
405
406 TIMEQ_CALLBACK(main_checkauths) {
407     int next_call = 600;
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;
414         }
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"
418             MYSQL_RES *res;
419             MYSQL_ROW row;
420             int lastcheck;
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");
424             res = mysql_use();
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);
429                 } else 
430                     next_call = 300;
431             }
432         } else {
433             int pending;
434             if(now > check_start_time)
435                 pending = 86400 - now + check_start_time;
436             else
437                 pending = check_start_time - now;
438             if(pending < 600)
439                 next_call = pending;
440         }
441         
442     }
443     timeq_add(next_call, main_checkauths, NULL);
444 }
445
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)
457                     lusersbot = bot;
458             }
459             bot = lusersbot;
460             if(bot == NULL) bot = getBots(SOCKET_FLAG_READY, NULL);
461             putsock(bot, "LUSERS");
462         } else {
463             statistics_update();
464         }
465     } else
466         statistics_enabled = 0;
467 }
468
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];
473         /* parameters:
474          - visible users
475          - visible chanusers
476          - visible channels
477          - privmsg per minute
478          - commands per minute
479          - network users
480          - network channels
481         */
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;
485         system(command);
486     }
487 }
488
489 void write_log(int loglevel, const char *line, int len) {
490     SYNCHRONIZE(log_sync);
491     if(!daemonized && (print_loglevel & loglevel)) {
492         printf("%s", line);
493     } else if(!daemonized && loglevel == LOGLEVEL_ERROR) {
494         fprintf(stderr, "%s", line);
495     }
496     if(get_int_field("log.loglevel") & loglevel) {
497         if(!log_fptr) {
498             log_fptr = fopen(LOG_FILE, "a");
499             if(!log_fptr) goto write_log_end;
500         }
501         time_t rawtime;
502         struct tm *timeinfo;
503         time(&rawtime);
504         timeinfo = localtime(&rawtime);
505         char timestr[20];
506         int timepos = strftime(timestr, 20, "%x %X ", timeinfo);
507         fwrite(timestr, 1, timepos, log_fptr);
508         fwrite(line, 1, len, log_fptr);
509     }
510     write_log_end:
511     DESYNCHRONIZE(log_sync);
512 }
513
514 void putlog(int loglevel, const char *text, ...) {
515     va_list arg_list;
516     char logBuf[MAXLOGLEN];
517     int pos;
518     logBuf[0] = '\0';
519     va_start(arg_list, text);
520     pos = vsnprintf(logBuf, MAXLOGLEN - 1, text, arg_list);
521     va_end(arg_list);
522     if (pos < 0 || pos > (MAXLOGLEN - 1)) pos = MAXLOGLEN - 1;
523     logBuf[pos] = '\0';
524     write_log(loglevel, logBuf, pos);
525 }
526