added new auth-check security feature
[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 void * thread_main(void *arg) {
105     time_t socket_wait;
106     while(running) {
107         socket_wait = time(0) + SOCKET_SELECT_TIME;
108         do {
109             socket_loop(SOCKET_SELECT_TIME);
110         } while(time(0) < socket_wait);
111         clearTempUsers();
112         destroyEvents();
113     }
114     running_threads--;
115     return NULL;
116 }
117 #endif
118
119 int main(int argc, char *argv[]) {
120 main:
121     
122     start_time = time(0);
123     
124     #ifdef WIN32
125     int res;
126     WSADATA wsadata;
127     // Start Windows Sockets.
128     res = WSAStartup(MAKEWORD(2, 0), &wsadata);
129     if (res)
130     {
131         perror("Unable to start Windows Sockets");
132         return 0;
133     }
134     #endif
135     
136     if(!load_mysql_config()) return 0;
137     
138     statistics_enabled = get_int_field("statistics.enable");
139     
140     #ifdef HAVE_THREADS
141     THREAD_MUTEX_INIT(cache_sync);
142     THREAD_MUTEX_INIT(whohandler_sync);
143     THREAD_MUTEX_INIT(whohandler_mass_sync);
144     #endif
145     
146     queue_init();
147     init_sockets();
148     init_timeq();
149     init_lang();
150     ssl_init();
151     init_parser();
152     init_UserNode();
153     init_ChanNode();
154     init_ModeNode();
155     init_bind();
156         init_modcmd();
157     init_handleinfohandler();
158     init_tools();
159     register_commands();
160     init_bots();
161     init_DBHelper();
162     qserver_init();
163     
164     load_languages();
165     int update_minutes = get_int_field("statistics.frequency");
166     if(!update_minutes) update_minutes = 2;
167     timeq_add(update_minutes * 60 + 10, main_statistics, NULL);
168     
169     timeq_add(90, main_checkauths, NULL);
170     
171     int worker_threads = get_int_field("General.worker_threads");
172     if(!worker_threads) worker_threads = 1;
173     
174     running = 1;
175     #ifdef HAVE_THREADS
176     pthread_t tid[worker_threads];
177     int tid_id = 0;
178     for(tid_id = 0; tid_id < worker_threads; tid_id++) {
179         running_threads++;
180         pthread_create(&tid[tid_id], NULL, thread_main, NULL);
181     }
182     int usleep_delay = 1000000 / TICKS_PER_SECOND;
183     while(running) {
184         timeq_tick();
185         loop_bots();
186         qserver_loop();
187         queue_loop();
188         usleep(usleep_delay);
189     }
190     for(tid_id = 0; tid_id < worker_threads; tid_id++) {
191         pthread_join(tid[tid_id], NULL);
192     }
193     running_threads = 0;
194     #else
195     time_t socket_wait;
196     while(running) {
197         socket_wait = time(0) + SOCKET_SELECT_TIME;
198         do {
199             socket_loop(SOCKET_SELECT_TIME);
200         } while(time(0) < socket_wait);
201         timeq_tick();
202         loop_bots();
203         clearTempUsers();
204         destroyEvents();
205         qserver_loop();
206         queue_loop();
207     }
208     #endif
209     cleanup();
210     if(hard_restart) {
211         /* Append a NULL to the end of argv[]. */
212         char **restart_argv = (char **)alloca((argc + 1) * sizeof(char *));
213         memcpy(restart_argv, argv, argc * sizeof(char *));
214         restart_argv[argc] = NULL;
215         
216         #ifdef WIN32
217         execv(argv[0], (const char * const*)restart_argv);
218         #else
219         execv(argv[0], restart_argv);
220         #endif
221     }
222     goto main;
223 }
224
225 int stricmp (const char *s1, const char *s2)
226 {
227    if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
228    if (s2 == NULL) return *s1;
229    char c1, c2;
230    while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
231    {
232      if (*s1 == '\0') break;
233      ++s1; ++s2;
234    }
235    return c1 - c2;
236 }
237
238 int stricmplen (const char *s1, const char *s2, int len)
239 {
240    if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
241    if (s2 == NULL) return *s1;
242    char c1, c2;
243    int i = 0;
244    while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
245    {
246      i++;
247      if (*s1 == '\0') break;
248      ++s1; ++s2;
249      if(i == len) break;
250    }
251    return c1 - c2;
252 }
253
254 void restart_bot(int do_hard_restart) {
255     hard_restart = do_hard_restart;
256     running = 0;
257 }
258
259 void stop_bot() {
260     cleanup();
261     exit(0);
262 }
263
264 void reload_config() {
265     loadConfig("neonserv.conf");
266 }
267
268 static int getCurrentSecondsOfDay() {
269     time_t now = time(0);
270     struct tm *timeofday = localtime(&now);
271     int seconds = 0;
272     seconds += timeofday->tm_hour * 3600;
273     seconds += timeofday->tm_min * 60;
274     seconds += timeofday->tm_sec;
275     return seconds;
276 }
277
278 static AUTHLOOKUP_CALLBACK(main_checkauths_callback) {
279     //check if registered is still valid
280     MYSQL_RES *res;
281     MYSQL_ROW row;
282     printf_mysql_query("SELECT `user_id`, `user_registered` FROM `users` WHERE `user_user` = '%s'", escape_string(auth));
283     res = mysql_use();
284     if ((row = mysql_fetch_row(res)) != NULL) {
285         if(!exists || (strcmp(row[1], "0") && registered != atoi(row[1]))) {
286             //User is no longer valid! Delete it...
287             deleteUser(atoi(row[0]));
288             char *alertchan = get_string_field("General.CheckAuths.alertchan");
289             if(alertchan) {
290                 struct ChanNode *alertchan_chan = getChanByName(alertchan);
291                 struct ClientSocket *alertclient;
292                 if(alertchan_chan && (alertclient = getChannelBot(alertchan_chan, 0)) != NULL) {
293                     putsock(alertclient, "PRIVMSG %s :Deleted User %s", alertchan_chan->name, auth);
294                 }
295             }
296         } else if(exists && !strcmp(row[1], "0")) {
297             printf_mysql_query("UPDATE `users` SET `user_registered` = '%lu', `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", (unsigned long) registered, row[0]);
298         } else {
299             printf_mysql_query("UPDATE `users` SET `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", row[0]);
300         }
301     }
302 }
303
304 TIMEQ_CALLBACK(main_checkauths) {
305     int next_call = 600;
306     if(get_int_field("General.CheckAuths.enabled")) {
307         int check_start_time = get_int_field("General.CheckAuths.start_time") * 3600;
308         int duration = get_int_field("General.CheckAuths.duration") * 60;
309         int now = getCurrentSecondsOfDay();
310         if(now < check_start_time && check_start_time+duration >= 86400) {
311             check_start_time -= 86400;
312         }
313         if(now >= check_start_time && now < (check_start_time + duration)) {
314             next_call = get_int_field("General.CheckAuths.interval");
315             //get the "longest-unchecked-user"
316             MYSQL_RES *res;
317             MYSQL_ROW row;
318             int lastcheck;
319             time_t unixtime = time(0);
320             int min_unckecked = get_int_field("General.CheckAuths.min_unckecked");
321             printf_mysql_query("SELECT `user_user`, `user_lastcheck` FROM `users` ORDER BY `user_lastcheck` ASC LIMIT 1");
322             res = mysql_use();
323             if ((row = mysql_fetch_row(res)) != NULL) {
324                 lastcheck = atoi(row[1]);
325                 if(!lastcheck || unixtime - lastcheck >= min_unckecked) {
326                     lookup_authname(row[0], main_checkauths_callback, NULL);
327                 } else 
328                     next_call = 300;
329             }
330         } else {
331             int pending;
332             if(now > check_start_time)
333                 pending = 86400 - now + check_start_time;
334             else
335                 pending = check_start_time - now;
336             if(pending < 600)
337                 next_call = pending;
338         }
339         
340     }
341     timeq_add(next_call, main_checkauths, NULL);
342 }
343
344 TIMEQ_CALLBACK(main_statistics) {
345     int update_minutes = get_int_field("statistics.frequency");
346     if(!update_minutes) update_minutes = 2;
347     timeq_add(update_minutes * 60, main_statistics, NULL);
348     if(get_int_field("statistics.enable")) {
349         statistics_enabled = 1;
350         statistics_requested_lusers = 1;
351         if(get_int_field("statistics.include_lusers")) {
352             struct ClientSocket *bot, *lusersbot = NULL;
353             for(bot = getBots(SOCKET_FLAG_READY, NULL); bot; bot = getBots(SOCKET_FLAG_READY, bot)) {
354                 if(bot->flags & SOCKET_FLAG_PREFERRED)
355                     lusersbot = bot;
356             }
357             bot = lusersbot;
358             if(bot == NULL) bot = getBots(SOCKET_FLAG_READY, NULL);
359             putsock(bot, "LUSERS");
360         } else {
361             statistics_update();
362         }
363     } else
364         statistics_enabled = 0;
365 }
366
367 void statistics_update() {
368     if(get_int_field("statistics.enable") && statistics_requested_lusers && get_string_field("statistics.execute")) {
369         statistics_requested_lusers = 0;
370         char command[MAXLEN];
371         /* parameters:
372          - visible users
373          - visible chanusers
374          - visible channels
375          - privmsg per minute
376          - commands per minute
377          - network users
378          - network channels
379         */
380         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);
381         statistics_privmsg = 0;
382         statistics_commands = 0;
383         system(command);
384     }
385 }