added small memory debugger to detect memory leaks
[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
42 time_t start_time;
43 static int running, hard_restart;
44 static int statistics_requested_lusers = 0;
45 int statistics_enabled;
46 TIMEQ_CALLBACK(main_statistics);
47 TIMEQ_CALLBACK(main_checkauths);
48 static int process_argc;
49 static char **process_argv;
50 #ifdef HAVE_THREADS
51 int running_threads;
52 pthread_mutex_t cache_sync;
53 pthread_mutex_t whohandler_sync, whohandler_mass_sync;
54 #endif
55
56 void cleanup() {
57     free_sockets();
58     qserver_free();
59     free_parser();
60     free_UserNode();
61     free_ChanNode();
62     free_bind();
63     free_modcmd();
64     free_whoqueue();
65     free_bots();
66     free_mysql();
67     free_handleinfohandler();
68     free_lang();
69 }
70
71 static int load_mysql_config() {
72     char *mysql_host, *mysql_user, *mysql_pass, *mysql_base;
73     int mysql_serverport;
74     if(loadConfig("neonserv.conf")) {
75         mysql_host = get_string_field("MySQL.host");
76         if(!mysql_host) {
77             perror("invalid neonserv.conf: missing MySQL.host");
78             return 0;
79         }
80         mysql_serverport = get_int_field("MySQL.port");
81         if(!mysql_serverport)
82             mysql_serverport = 3306;
83         mysql_user = get_string_field("MySQL.user");
84         if(!mysql_user) {
85             perror("invalid neonserv.conf: missing MySQL.user");
86             return 0;
87         }
88         mysql_pass = get_string_field("MySQL.pass");
89         if(!mysql_pass) {
90             perror("invalid neonserv.conf: missing MySQL.pass");
91             return 0;
92         }
93         mysql_base = get_string_field("MySQL.base");
94         if(!mysql_base) {
95             perror("invalid neonserv.conf: missing MySQL base");
96             return 0;
97         }
98     } else {
99         perror("Unable to load neonserv.conf");
100         return 0;
101     }
102     init_mysql(mysql_host, mysql_serverport, mysql_user, mysql_pass, mysql_base);
103     return 1;
104 }
105
106 #ifdef HAVE_THREADS
107 pthread_t *current_threads = NULL;
108
109 void * thread_main(void *arg) {
110     time_t socket_wait;
111     while(running) {
112         socket_wait = time(0) + SOCKET_SELECT_TIME;
113         do {
114             socket_loop(SOCKET_SELECT_TIME);
115         } while(time(0) < socket_wait);
116         clearTempUsers();
117         destroyEvents();
118     }
119     running_threads--;
120     return NULL;
121 }
122
123 int getCurrentThreadID() {
124     if(!current_threads) return 0;
125     int i;
126     unsigned int my_tid = (unsigned int) pthread_self_tid();
127     for(i = 0; i < running_threads; i++) {
128         #ifdef WIN32
129         if((unsigned int) current_threads[i].p == my_tid)
130         #else
131         if((unsigned int) current_threads[i] == my_tid)
132         #endif
133             return i+1;
134     }
135     return 0;
136 }
137
138 #endif
139
140 int main(int argc, char *argv[]) {
141 main:
142     process_argv = argv;
143     process_argc = argc;
144     
145     signal(SIGABRT, sighandler);
146     signal(SIGFPE, sighandler);
147     signal(SIGILL, sighandler);
148     signal(SIGINT, sighandler);
149     signal(SIGSEGV, sighandler);
150     signal(SIGTERM, sighandler);
151     
152     #ifdef ENABLE_MEMORY_DEBUG
153     initMemoryDebug();
154     #endif
155     
156     start_time = time(0);
157     
158     #ifdef WIN32
159     int res;
160     WSADATA wsadata;
161     // Start Windows Sockets.
162     res = WSAStartup(MAKEWORD(2, 0), &wsadata);
163     if (res)
164     {
165         perror("Unable to start Windows Sockets");
166         return 0;
167     }
168     #endif
169     
170     if(!load_mysql_config()) return 0;
171     
172     statistics_enabled = get_int_field("statistics.enable");
173     
174     #ifdef HAVE_THREADS
175     THREAD_MUTEX_INIT(cache_sync);
176     THREAD_MUTEX_INIT(whohandler_sync);
177     THREAD_MUTEX_INIT(whohandler_mass_sync);
178     #endif
179     
180     queue_init();
181     init_sockets();
182     init_timeq();
183     init_lang();
184     ssl_init();
185     init_parser();
186     init_UserNode();
187     init_ChanNode();
188     init_ModeNode();
189     init_bind();
190         init_modcmd();
191     init_handleinfohandler();
192     init_tools();
193     register_commands();
194     init_bots();
195     init_DBHelper();
196     qserver_init();
197     
198     load_languages();
199     int update_minutes = get_int_field("statistics.frequency");
200     if(!update_minutes) update_minutes = 2;
201     timeq_add(update_minutes * 60 + 10, main_statistics, NULL);
202     
203     timeq_add(90, main_checkauths, NULL);
204     
205     int worker_threads = get_int_field("General.worker_threads");
206     if(!worker_threads) worker_threads = 1;
207     running = 1;
208     #ifdef HAVE_THREADS
209     int tid_id = 0;
210     current_threads = calloc(worker_threads, sizeof(*current_threads));
211     for(tid_id = 0; tid_id < worker_threads; tid_id++) {
212         running_threads++;
213         pthread_create(&current_threads[tid_id], NULL, thread_main, NULL);
214     }
215     int usleep_delay = 1000000 / TICKS_PER_SECOND;
216     while(running) {
217         timeq_tick();
218         loop_bots();
219         qserver_loop();
220         queue_loop();
221         usleep(usleep_delay);
222     }
223     for(tid_id = 0; tid_id < worker_threads; tid_id++) {
224         pthread_join(current_threads[tid_id], NULL);
225     }
226     running_threads = 0;
227     #else
228     time_t socket_wait;
229     while(running) {
230         socket_wait = time(0) + SOCKET_SELECT_TIME;
231         do {
232             socket_loop(SOCKET_SELECT_TIME);
233         } while(time(0) < socket_wait);
234         timeq_tick();
235         loop_bots();
236         clearTempUsers();
237         destroyEvents();
238         qserver_loop();
239         queue_loop();
240     }
241     #endif
242     cleanup();
243     if(hard_restart) {
244         restart_process();
245     }
246     goto main;
247 }
248
249 void restart_process() {
250     /* Append a NULL to the end of argv[]. */
251     char **restart_argv = (char **)alloca((process_argc + 1) * sizeof(char *));
252     memcpy(restart_argv, process_argv, process_argc * sizeof(char *));
253     restart_argv[process_argc] = NULL;
254     #ifdef WIN32
255     execv(process_argv[0], (const char * const*)restart_argv);
256     #else
257     execv(process_argv[0], restart_argv);
258     #endif
259 }
260
261 int stricmp (const char *s1, const char *s2)
262 {
263    if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
264    if (s2 == NULL) return *s1;
265    char c1, c2;
266    while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
267    {
268      if (*s1 == '\0') break;
269      ++s1; ++s2;
270    }
271    return c1 - c2;
272 }
273
274 int stricmplen (const char *s1, const char *s2, int len)
275 {
276    if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
277    if (s2 == NULL) return *s1;
278    char c1, c2;
279    int i = 0;
280    while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
281    {
282      i++;
283      if (*s1 == '\0') break;
284      ++s1; ++s2;
285      if(i == len) break;
286    }
287    return c1 - c2;
288 }
289
290 void restart_bot(int do_hard_restart) {
291     hard_restart = do_hard_restart;
292     running = 0;
293 }
294
295 void stop_bot() {
296     cleanup();
297     exit(0);
298 }
299
300 void reload_config() {
301     loadConfig("neonserv.conf");
302 }
303
304 static int getCurrentSecondsOfDay() {
305     time_t now = time(0);
306     struct tm *timeofday = localtime(&now);
307     int seconds = 0;
308     seconds += timeofday->tm_hour * 3600;
309     seconds += timeofday->tm_min * 60;
310     seconds += timeofday->tm_sec;
311     return seconds;
312 }
313
314 static AUTHLOOKUP_CALLBACK(main_checkauths_callback) {
315     //check if registered is still valid
316     MYSQL_RES *res;
317     MYSQL_ROW row;
318     printf_mysql_query("SELECT `user_id`, `user_registered` FROM `users` WHERE `user_user` = '%s'", escape_string(auth));
319     res = mysql_use();
320     if ((row = mysql_fetch_row(res)) != NULL) {
321         if(!exists || (strcmp(row[1], "0") && registered != atoi(row[1]))) {
322             //User is no longer valid! Delete it...
323             deleteUser(atoi(row[0]));
324             char *alertchan = get_string_field("General.CheckAuths.alertchan");
325             if(alertchan) {
326                 struct ChanNode *alertchan_chan = getChanByName(alertchan);
327                 struct ClientSocket *alertclient;
328                 if(alertchan_chan && (alertclient = getChannelBot(alertchan_chan, 0)) != NULL) {
329                     putsock(alertclient, "PRIVMSG %s :Deleted User %s", alertchan_chan->name, auth);
330                 }
331             }
332         } else if(exists && !strcmp(row[1], "0")) {
333             printf_mysql_query("UPDATE `users` SET `user_registered` = '%lu', `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", (unsigned long) registered, row[0]);
334         } else {
335             printf_mysql_query("UPDATE `users` SET `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", row[0]);
336         }
337     }
338 }
339
340 TIMEQ_CALLBACK(main_checkauths) {
341     int next_call = 600;
342     if(get_int_field("General.CheckAuths.enabled")) {
343         int check_start_time = get_int_field("General.CheckAuths.start_time") * 3600;
344         int duration = get_int_field("General.CheckAuths.duration") * 60;
345         int now = getCurrentSecondsOfDay();
346         if(now < check_start_time && check_start_time+duration >= 86400) {
347             check_start_time -= 86400;
348         }
349         if(now >= check_start_time && now < (check_start_time + duration)) {
350             next_call = get_int_field("General.CheckAuths.interval");
351             //get the "longest-unchecked-user"
352             MYSQL_RES *res;
353             MYSQL_ROW row;
354             int lastcheck;
355             time_t unixtime = time(0);
356             int min_unckecked = get_int_field("General.CheckAuths.min_unckecked");
357             printf_mysql_query("SELECT `user_user`, `user_lastcheck` FROM `users` ORDER BY `user_lastcheck` ASC LIMIT 1");
358             res = mysql_use();
359             if ((row = mysql_fetch_row(res)) != NULL) {
360                 lastcheck = atoi(row[1]);
361                 if(!lastcheck || unixtime - lastcheck >= min_unckecked) {
362                     lookup_authname(row[0], main_checkauths_callback, NULL);
363                 } else 
364                     next_call = 300;
365             }
366         } else {
367             int pending;
368             if(now > check_start_time)
369                 pending = 86400 - now + check_start_time;
370             else
371                 pending = check_start_time - now;
372             if(pending < 600)
373                 next_call = pending;
374         }
375         
376     }
377     timeq_add(next_call, main_checkauths, NULL);
378 }
379
380 TIMEQ_CALLBACK(main_statistics) {
381     int update_minutes = get_int_field("statistics.frequency");
382     if(!update_minutes) update_minutes = 2;
383     timeq_add(update_minutes * 60, main_statistics, NULL);
384     if(get_int_field("statistics.enable")) {
385         statistics_enabled = 1;
386         statistics_requested_lusers = 1;
387         if(get_int_field("statistics.include_lusers")) {
388             struct ClientSocket *bot, *lusersbot = NULL;
389             for(bot = getBots(SOCKET_FLAG_READY, NULL); bot; bot = getBots(SOCKET_FLAG_READY, bot)) {
390                 if(bot->flags & SOCKET_FLAG_PREFERRED)
391                     lusersbot = bot;
392             }
393             bot = lusersbot;
394             if(bot == NULL) bot = getBots(SOCKET_FLAG_READY, NULL);
395             putsock(bot, "LUSERS");
396         } else {
397             statistics_update();
398         }
399     } else
400         statistics_enabled = 0;
401 }
402
403 void statistics_update() {
404     if(get_int_field("statistics.enable") && statistics_requested_lusers && get_string_field("statistics.execute")) {
405         statistics_requested_lusers = 0;
406         char command[MAXLEN];
407         /* parameters:
408          - visible users
409          - visible chanusers
410          - visible channels
411          - privmsg per minute
412          - commands per minute
413          - network users
414          - network channels
415         */
416         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);
417         statistics_privmsg = 0;
418         statistics_commands = 0;
419         system(command);
420     }
421 }