f3afaaf8a18c97a9bfd50a452eac5c2bd2a9feb5
[NeonServV5.git] / src / main.c
1 /* main.c - NeonServ v5.4
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 "ConfigParser.h"
38 #include "ssl.h"
39 #include "QServer.h"
40 #include "version.h"
41 #include "modules.h"
42 #include "module_commands.h"
43
44 time_t start_time;
45 static int running, hard_restart;
46 static int statistics_requested_lusers = 0;
47 int statistics_enabled;
48 TIMEQ_CALLBACK(main_statistics);
49 TIMEQ_CALLBACK(main_checkauths);
50 static int daemonized = 0;
51 static int print_loglevel = 0;
52 static FILE *log_fptr = NULL;
53 static int process_argc;
54 static char **process_argv;
55 #ifdef HAVE_THREADS
56 int running_threads;
57 pthread_mutex_t cache_sync;
58 pthread_mutex_t whohandler_sync, whohandler_mass_sync;
59 static pthread_mutex_t log_sync;
60 #endif
61
62 static void check_firstrun();
63
64 void cleanup() {
65     stop_modules();
66     free_sockets();
67     qserver_free();
68     free_parser();
69     free_UserNode();
70     free_ChanNode();
71     free_bind();
72     free_modcmd();
73     free_whoqueue();
74     free_mysql();
75     free_handleinfohandler();
76     free_lang();
77 }
78
79 static int load_mysql_config() {
80     char *mysql_host, *mysql_user, *mysql_pass, *mysql_base;
81     int mysql_serverport;
82     
83     mysql_host = get_string_field("MySQL.host");
84     if(!mysql_host) {
85         perror("invalid neonserv.conf: missing MySQL.host");
86         return 0;
87     }
88     mysql_serverport = get_int_field("MySQL.port");
89     if(!mysql_serverport)
90         mysql_serverport = 3306;
91     mysql_user = get_string_field("MySQL.user");
92     if(!mysql_user) {
93         perror("invalid neonserv.conf: missing MySQL.user");
94         return 0;
95     }
96     mysql_pass = get_string_field("MySQL.pass");
97     if(!mysql_pass) {
98         perror("invalid neonserv.conf: missing MySQL.pass");
99         return 0;
100     }
101     mysql_base = get_string_field("MySQL.base");
102     if(!mysql_base) {
103         perror("invalid neonserv.conf: missing MySQL base");
104         return 0;
105     }
106     init_mysql(mysql_host, mysql_serverport, mysql_user, mysql_pass, mysql_base);
107     return 1;
108 }
109
110 #ifdef HAVE_THREADS
111 pthread_t *current_threads = NULL;
112
113 void * thread_main(void *arg) {
114     time_t socket_wait;
115     while(running) {
116         socket_wait = time(0) + SOCKET_SELECT_TIME;
117         do {
118             if(!socket_loop(SOCKET_SELECT_TIME)) {
119                 if(!running) break;
120                 putlog(LOGLEVEL_ERROR, "No more active Bots... shutting down.\n");
121                 cleanup();
122                 exit(0);
123             }
124         } while(time(0) < socket_wait);
125         if(!running) break;
126         clearTempUsers();
127         destroyEvents();
128         mysql_free();
129     }
130     running_threads--;
131     return NULL;
132 }
133
134 int getCurrentThreadID() {
135     if(!current_threads) return 0;
136     int i;
137     unsigned int my_tid = (unsigned int) pthread_self_tid();
138     for(i = 0; i < running_threads; i++) {
139         #ifdef WIN32
140         if((unsigned int) current_threads[i].p == my_tid)
141         #else
142         if((unsigned int) current_threads[i] == my_tid)
143         #endif
144             return i+1;
145     }
146     return 0;
147 }
148
149 #endif
150
151 void exit_daemon() {
152     running = 0;
153     if(daemonized) {
154         remove(PID_FILE);
155     }
156     if(log_fptr) {
157         fclose(log_fptr);
158         log_fptr = NULL;
159     }
160 }
161
162 int main(int argc, char *argv[]) {
163     int run_as_daemon = 1;
164     int c;
165     process_argv = argv;
166     process_argc = argc;
167     printf("NeonServ v%s\n\n", NEONSERV_VERSION);
168     struct option options[] = {
169         {"show", 1, 0, 's'},
170         {"foreground", 0, 0, 'f'},
171         {"help", 0, 0, 'h'},
172         {"version", 0, 0, 'v'},
173         {0, 0, 0, 0}
174     };
175     while ((c = getopt_long(argc, argv, "s:fvh", options, NULL)) != -1) {
176         switch (c) {
177         case 's':
178             print_loglevel = atoi(optarg);
179             break;
180         case 'f':
181             run_as_daemon = 0;
182             break;
183         case 'v':
184             printf("Version: %s.%d (%s)\n", NEONSERV_VERSION, patchlevel, (strcmp(revision, "") ? revision : "-"));
185             printf("Build: #%s %s (%s lines, " COMPILER ")\n", compilation, creation, codelines);
186             exit(0);
187             break;
188         case 'h':
189             printf("Usage: ./neonserv [-s loglevel] [-f] [-h|-v]\n");
190             printf(" -s, --show           show log lines matching loglevel in stdout.\n");
191             printf(" -f, --foreground     run NeonServ in the foreground.\n");
192             printf(" -h, --help           prints this usage message.\n");
193             printf(" -v, --version        prints this program's version.\n");
194             exit(0);
195             break;
196         }
197     }
198     #ifndef WIN32
199     if(geteuid() == 0 || getuid() == 0) {
200         fprintf(stderr, "NeonServ may not be run with super user privileges.\n");
201         exit(0);
202     }
203     #endif
204     #ifdef ENABLE_MEMORY_DEBUG
205     initMemoryDebug();
206     #endif
207     if(!loadConfig(CONF_FILE)) {
208         fprintf(stderr, "Unable to load " CONF_FILE "\n");
209         exit(0);
210     }
211     #if HAVE_THREADS
212     THREAD_MUTEX_INIT(log_sync);
213     #endif
214     if(!load_mysql_config()) {
215         fprintf(stderr, "Unable to connect to MySQL\n");
216         exit(0);
217     }
218     check_firstrun();
219     char **modulelist = get_all_fieldnames("modules");
220     if(!modulelist || !modulelist[0]) {
221         fprintf(stderr, "no modules loaded... Please update your configuration!\n");
222         exit(0);
223     }
224     free(modulelist);
225     if (run_as_daemon) {
226         #ifndef WIN32
227         /* Attempt to fork into the background if daemon mode is on. */
228         pid_t pid = fork();
229         if (pid < 0) {
230             fprintf(stderr, "Unable to fork: %s\n", strerror(errno));
231         } else if (pid > 0) {
232             printf("Forking into the background (pid: %d)...\n", pid);
233             putlog(LOGLEVEL_INFO, "Forking into the background (pid: %d)...\n", pid);
234             exit(0);
235         }
236         setsid();
237         daemonized = 1;
238         atexit(exit_daemon);
239         FILE *pidfile = fopen(PID_FILE, "w");
240         if (pidfile == NULL) {
241             fprintf(stderr, "Unable to create PID file: %s\n", strerror(errno));
242             putlog(LOGLEVEL_ERROR, "Unable to create PID file: %s\n", strerror(errno));
243         } else {
244             fprintf(pidfile, "%i\n", (int)getpid());
245             fclose(pidfile);
246         }
247                 FILE *retn;
248         fclose(stdin); retn = fopen("/dev/null", "r");
249         fclose(stdout); retn = fopen("/dev/null", "w");
250         fclose(stderr); retn = fopen("/dev/null", "w");
251         #endif
252     }
253     
254 main:
255     signal(SIGABRT, sighandler);
256     signal(SIGFPE, sighandler);
257     signal(SIGILL, sighandler);
258     signal(SIGINT, sighandler);
259     signal(SIGSEGV, sighandler);
260     signal(SIGTERM, sighandler);
261     
262     start_time = time(0);
263     
264     #ifdef WIN32
265     int res;
266     WSADATA wsadata;
267     // Start Windows Sockets.
268     res = WSAStartup(MAKEWORD(2, 0), &wsadata);
269     if (res)
270     {
271         perror("Unable to start Windows Sockets");
272         return 0;
273     }
274     #endif
275     
276     statistics_enabled = get_int_field("statistics.enable");
277     
278     #ifdef HAVE_THREADS
279     THREAD_MUTEX_INIT(cache_sync);
280     THREAD_MUTEX_INIT(whohandler_sync);
281     THREAD_MUTEX_INIT(whohandler_mass_sync);
282     #endif
283     
284     queue_init();
285     init_sockets();
286     init_timeq();
287     init_lang();
288     ssl_init();
289     init_parser();
290     init_UserNode();
291     init_ChanNode();
292     init_ModeNode();
293     init_bind();
294         init_modcmd();
295     register_module_commands();
296     init_handleinfohandler();
297     init_tools();
298     loadModules();
299     init_bots();
300     init_DBHelper();
301     qserver_init();
302     
303     load_languages();
304     int update_minutes = get_int_field("statistics.frequency");
305     if(!update_minutes) update_minutes = 2;
306     timeq_add(update_minutes * 60 + 10, 0, main_statistics, NULL);
307     
308     timeq_add(90, 0, main_checkauths, NULL);
309     
310     int worker_threads = get_int_field("General.worker_threads");
311     if(!worker_threads) worker_threads = 1;
312     running = 1;
313     #ifdef HAVE_THREADS
314     int tid_id = 0;
315     current_threads = calloc(worker_threads, sizeof(*current_threads));
316     for(tid_id = 0; tid_id < worker_threads; tid_id++) {
317         running_threads++;
318         pthread_create(&current_threads[tid_id], NULL, thread_main, NULL);
319     }
320     int usleep_delay = 1000000 / TICKS_PER_SECOND;
321     while(running) {
322         timeq_tick();
323         loop_modules();
324         qserver_loop();
325         queue_loop();
326         mysql_free();
327         usleep(usleep_delay);
328     }
329     for(tid_id = 0; tid_id < worker_threads; tid_id++) {
330         pthread_join(current_threads[tid_id], NULL);
331     }
332     running_threads = 0;
333     #else
334     time_t socket_wait;
335     while(running) {
336         socket_wait = time(0) + SOCKET_SELECT_TIME;
337         do {
338             if(!socket_loop(SOCKET_SELECT_TIME)) {
339                 putlog(LOGLEVEL_ERROR, "No more active Bots... shutting down.\n");
340                 cleanup();
341                 exit(0);
342             }
343         } while(time(0) < socket_wait);
344         timeq_tick();
345         loop_modules();
346         clearTempUsers();
347         destroyEvents();
348         qserver_loop();
349         queue_loop();
350         mysql_free();
351     }
352     #endif
353     cleanup();
354     if(hard_restart) {
355         restart_process();
356     }
357     goto main;
358 }
359
360 void restart_process() {
361     /* Append a NULL to the end of argv[]. */
362     char **restart_argv = (char **)alloca((process_argc + 1) * sizeof(char *));
363     memcpy(restart_argv, process_argv, process_argc * sizeof(char *));
364     restart_argv[process_argc] = NULL;
365     #ifdef WIN32
366     execv(process_argv[0], (const char * const*)restart_argv);
367     #else
368     execv(process_argv[0], restart_argv);
369     #endif
370 }
371
372 int stricmp (const char *s1, const char *s2)
373 {
374    if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
375    if (s2 == NULL) return *s1;
376    char c1, c2;
377    while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
378    {
379      if (*s1 == '\0') break;
380      ++s1; ++s2;
381    }
382    return c1 - c2;
383 }
384
385 int stricmplen (const char *s1, const char *s2, int len)
386 {
387    if (s1 == NULL) return s2 == NULL ? 0 : -(*s2);
388    if (s2 == NULL) return *s1;
389    char c1, c2;
390    int i = 0;
391    while ((c1 = tolower (*s1)) == (c2 = tolower (*s2)))
392    {
393      i++;
394      if (*s1 == '\0') break;
395      ++s1; ++s2;
396      if(i == len) break;
397    }
398    return c1 - c2;
399 }
400
401 void restart_bot(int do_hard_restart) {
402     hard_restart = do_hard_restart;
403     running = 0;
404 }
405
406 void stop_bot() {
407     cleanup();
408     exit(0);
409 }
410
411 void reload_config() {
412     loadConfig(CONF_FILE);
413 }
414
415 static int getCurrentSecondsOfDay() {
416     time_t now = time(0);
417     struct tm *timeofday = localtime(&now);
418     int seconds = 0;
419     seconds += timeofday->tm_hour * 3600;
420     seconds += timeofday->tm_min * 60;
421     seconds += timeofday->tm_sec;
422     return seconds;
423 }
424
425 static AUTHLOOKUP_CALLBACK(main_checkauths_callback) {
426     //check if registered is still valid
427     MYSQL_RES *res;
428     MYSQL_ROW row;
429     printf_mysql_query("SELECT `user_id`, `user_registered` FROM `users` WHERE `user_user` = '%s'", escape_string(auth));
430     res = mysql_use();
431     if ((row = mysql_fetch_row(res)) != NULL) {
432         int diff = registered - atoi(row[1]);
433         if(diff < 0)
434             diff *= -1;
435         if(!exists || (strcmp(row[1], "0") && diff > 86400)) {
436             //User is no longer valid! Delete it...
437             deleteUser(atoi(row[0]));
438             char *alertchan = get_string_field("General.CheckAuths.alertchan");
439             if(alertchan) {
440                 char reason[MAXLEN];
441                 if(!exists) {
442                     strcpy(reason, "USER_NOT_EXISTS");
443                 } else {
444                     sprintf(reason, "USER_REGISTERED_MISSMATCH: %lu, expected %d (diff: %d)", (unsigned long) registered, atoi(row[1]), diff);
445                 }
446                 struct ChanNode *alertchan_chan = getChanByName(alertchan);
447                 struct ClientSocket *alertclient;
448                 if(alertchan_chan && (alertclient = getChannelBot(alertchan_chan, 0)) != NULL) {
449                     putsock(alertclient, "PRIVMSG %s :Deleted User %s (%s)", alertchan_chan->name, auth, reason);
450                 }
451             }
452         } else if(exists && !strcmp(row[1], "0")) {
453             printf_mysql_query("UPDATE `users` SET `user_registered` = '%lu', `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", (unsigned long) registered, row[0]);
454         } else {
455             printf_mysql_query("UPDATE `users` SET `user_lastcheck` = UNIX_TIMESTAMP() WHERE `user_id` = '%s'", row[0]);
456         }
457     }
458 }
459
460 TIMEQ_CALLBACK(main_checkauths) {
461     int next_call = 600;
462     if(get_int_field("General.CheckAuths.enabled")) {
463         int check_start_time = get_int_field("General.CheckAuths.start_time") * 3600;
464         int duration = get_int_field("General.CheckAuths.duration") * 60;
465         int now = getCurrentSecondsOfDay();
466         if(now < check_start_time && check_start_time+duration >= 86400) {
467             check_start_time -= 86400;
468         }
469         if(now >= check_start_time && now < (check_start_time + duration)) {
470             next_call = get_int_field("General.CheckAuths.interval");
471             //get the "longest-unchecked-user"
472             MYSQL_RES *res;
473             MYSQL_ROW row;
474             int lastcheck;
475             time_t unixtime = time(0);
476             int min_unckecked = get_int_field("General.CheckAuths.min_unckecked");
477             printf_mysql_query("SELECT `user_user`, `user_lastcheck` FROM `users` ORDER BY `user_lastcheck` ASC LIMIT 1");
478             res = mysql_use();
479             if ((row = mysql_fetch_row(res)) != NULL) {
480                 lastcheck = atoi(row[1]);
481                 if(!lastcheck || unixtime - lastcheck >= min_unckecked) {
482                     lookup_authname(row[0], 0, main_checkauths_callback, NULL);
483                 } else 
484                     next_call = 300;
485             }
486         } else {
487             int pending;
488             if(now > check_start_time)
489                 pending = 86400 - now + check_start_time;
490             else
491                 pending = check_start_time - now;
492             if(pending < 600)
493                 next_call = pending;
494         }
495         
496     }
497     timeq_add(next_call, 0, main_checkauths, NULL);
498 }
499
500 TIMEQ_CALLBACK(main_statistics) {
501     int update_minutes = get_int_field("statistics.frequency");
502     if(!update_minutes) update_minutes = 2;
503     timeq_add(update_minutes * 60, 0, main_statistics, NULL);
504     if(get_int_field("statistics.enable")) {
505         statistics_enabled = 1;
506         statistics_requested_lusers = 1;
507         if(get_int_field("statistics.include_lusers")) {
508             struct ClientSocket *bot, *lusersbot = NULL;
509             for(bot = getBots(SOCKET_FLAG_READY, NULL); bot; bot = getBots(SOCKET_FLAG_READY, bot)) {
510                 if(bot->flags & SOCKET_FLAG_PREFERRED)
511                     lusersbot = bot;
512             }
513             bot = lusersbot;
514             if(bot == NULL) bot = getBots(SOCKET_FLAG_READY, NULL);
515             putsock(bot, "LUSERS");
516         } else {
517             statistics_update();
518         }
519     } else
520         statistics_enabled = 0;
521 }
522
523 int statistics_update() {
524     if(get_int_field("statistics.enable") && statistics_requested_lusers && get_string_field("statistics.execute")) {
525         statistics_requested_lusers = 0;
526         char command[MAXLEN];
527         /* parameters:
528          - visible users
529          - visible chanusers
530          - visible channels
531          - privmsg per minute
532          - commands per minute
533          - network users
534          - network channels
535         */
536         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);
537         statistics_privmsg = 0;
538         statistics_commands = 0;
539         return system(command);
540     }
541         return -1;
542 }
543
544 time_t getStartTime() {
545     return start_time;
546 }
547
548 int getRunningThreads() {
549         #ifdef HAVE_THREADS
550     return running_threads;
551         #else
552         return 1;
553         #endif
554 }
555
556 void write_log(int loglevel, const char *line, int len) {
557     SYNCHRONIZE(log_sync);
558     if(!daemonized && (print_loglevel & loglevel)) {
559         printf("%s", line);
560     } else if(!daemonized && loglevel == LOGLEVEL_ERROR) {
561         fprintf(stderr, "%s", line);
562     }
563     if(get_int_field("log.loglevel") & loglevel) {
564         if(!log_fptr) {
565             log_fptr = fopen(LOG_FILE, "a");
566             if(!log_fptr) goto write_log_end;
567         }
568         time_t rawtime;
569         struct tm *timeinfo;
570         time(&rawtime);
571         timeinfo = localtime(&rawtime);
572         char timestr[20];
573         int timepos = strftime(timestr, 20, "%x %X ", timeinfo);
574         fwrite(timestr, 1, timepos, log_fptr);
575         fwrite(line, 1, len, log_fptr);
576     }
577     write_log_end:
578     DESYNCHRONIZE(log_sync);
579 }
580
581 void putlog(int loglevel, const char *text, ...) {
582     va_list arg_list;
583     char logBuf[MAXLOGLEN];
584     int pos;
585     logBuf[0] = '\0';
586     va_start(arg_list, text);
587     pos = vsnprintf(logBuf, MAXLOGLEN - 1, text, arg_list);
588     va_end(arg_list);
589     if (pos < 0 || pos > (MAXLOGLEN - 1)) pos = MAXLOGLEN - 1;
590     logBuf[pos] = '\0';
591     write_log(loglevel, logBuf, pos);
592 }
593
594 static void check_firstrun() {
595     MYSQL_RES *res;
596     MYSQL_ROW row;
597     printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_access` = 1000 LIMIT 1");
598     res = mysql_use();
599     if (mysql_fetch_row(res) == NULL) {
600         //first run!
601         printf("No superuser found...\n");
602         check_firstrun_admin:
603         printf("AuthServ account name of admin user: ");
604         char *ptr;
605         char adminuser[31];
606         ptr = fgets(adminuser, 30, stdin);
607         for(ptr = adminuser; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
608         if(strlen(adminuser) < 2) goto check_firstrun_admin;
609         printf_mysql_query("SELECT `user_id` FROM `users` WHERE `user_user` = '%s'", escape_string(adminuser));
610         res = mysql_use();
611         if ((row = mysql_fetch_row(res)) != NULL)
612             printf_mysql_query("UPDATE `users` SET `user_access` = 1000 WHERE `user_id` = '%s'", row[0]);
613         else
614             printf_mysql_query("INSERT INTO `users` (`user_user`, `user_access`) VALUES ('%s', 1000)", escape_string(adminuser));
615     }
616     printf_mysql_query("SELECT `id` FROM `bots` WHERE `active` = 1 LIMIT 1");
617     res = mysql_use();
618     if (mysql_fetch_row(res) == NULL) {
619         //no bot active
620         printf("No active bot found...\n\n");
621         printf("ADD NEW BOT\n");
622         char *ptr;
623         char bot_nick[31];
624         check_firstrun_bot_nick:
625         printf("Nick: ");
626         ptr = fgets(bot_nick, 30, stdin);
627         for(ptr = bot_nick; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
628         if(strlen(bot_nick) < 2) goto check_firstrun_bot_nick;
629         char bot_ident[16];
630         check_firstrun_bot_ident:
631         printf("Ident: ");
632         ptr = fgets(bot_ident, 15, stdin);
633         for(ptr = bot_ident; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
634         if(strlen(bot_ident) < 2) goto check_firstrun_bot_ident;
635         char bot_realname[101];
636         check_firstrun_bot_realname:
637         printf("Realname: ");
638         ptr = fgets(bot_realname, 100, stdin);
639         for(ptr = bot_realname; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
640         if(strlen(bot_realname) < 2) goto check_firstrun_bot_realname;
641         char bot_server[101];
642         check_firstrun_bot_server:
643         printf("Server: [irc.onlinegamesnet.net] ");
644         ptr = fgets(bot_server, 100, stdin);
645         for(ptr = bot_server; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
646         if(*bot_server && strlen(bot_nick) < 5) goto check_firstrun_bot_server;
647         if(!*bot_server)
648             strcpy(bot_server, "irc.onlinegamesnet.net");
649         int bot_port;
650         char bot_port_buf[7];
651         printf("Port: [6667] ");
652         ptr = fgets(bot_port_buf, 6, stdin);
653         for(ptr = bot_port_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
654         if(!*bot_port_buf)
655             bot_port = 6667;
656         else
657             bot_port = atoi(bot_port_buf);
658         int bot_ssl;
659         char bot_ssl_buf[5];
660         check_firstrun_bot_ssl:
661         printf("SSL: [y/N] ");
662         ptr = fgets(bot_ssl_buf, 4, stdin);
663         for(ptr = bot_ssl_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
664         if(!*bot_ssl_buf || tolower(*bot_ssl_buf) == 'n')
665             bot_ssl = 0;
666         else if(tolower(*bot_ssl_buf) == 'y')
667             bot_ssl = 1;
668         else
669             goto check_firstrun_bot_ssl;
670         char bot_pass[101];
671         printf("Server Password: [] ");
672         ptr = fgets(bot_pass, 100, stdin);
673         for(ptr = bot_pass; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
674         int bot_maxchan;
675         char bot_maxchan_buf[5];
676         printf("MaxChannel: [20] ");
677         ptr = fgets(bot_maxchan_buf, 5, stdin);
678         for(ptr = bot_maxchan_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
679         if(*bot_maxchan_buf)
680             bot_maxchan = atoi(bot_maxchan_buf);
681         else
682             bot_maxchan = 20;
683         int bot_queue;
684         char bot_queue_buf[5];
685         check_firstrun_bot_queue:
686         printf("Queue (prevents excess floods): [Y/n] ");
687         ptr = fgets(bot_queue_buf, 4, stdin);
688         for(ptr = bot_queue_buf; *ptr; ptr++) { if(*ptr == '\n' || *ptr == '\r') *ptr = '\0'; }
689         if(!*bot_queue_buf || tolower(*bot_queue_buf) == 'y')
690             bot_queue = 1;
691         else if(tolower(*bot_queue_buf) == 'n')
692             bot_queue = 0;
693         else
694             goto check_firstrun_bot_queue;
695         printf_mysql_query("INSERT INTO `bots` (`active`, `nick`, `server`, `port`, `pass`, `ssl`, `ident`, `realname`, `botclass`, `textbot`, `queue`, `defaulttrigger`, `max_channels`) VALUES ('1', '%s', '%s', '%d', '%s', '%d', '%s', '%s', '1', '1', '%d', '+', '%d')", escape_string(bot_nick), escape_string(bot_server), bot_port, escape_string(bot_pass), bot_ssl, escape_string(bot_ident), escape_string(bot_realname), bot_queue, bot_maxchan);
696     }
697 }
698