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