1
0

main.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016
  1. /*
  2. * main.c -- handles:
  3. * core event handling
  4. * command line arguments
  5. * context and assert debugging
  6. *
  7. */
  8. #include "common.h"
  9. #include "main.h"
  10. #include "userent.h"
  11. #include "auth.h"
  12. #include "adns.h"
  13. #include "botcmd.h"
  14. #include "color.h"
  15. #include "dcc.h"
  16. #include "misc.h"
  17. #include "binary.h"
  18. #include "response.h"
  19. #include "thread.h"
  20. #include "settings.h"
  21. #include "misc_file.h"
  22. #include "net.h"
  23. #include "users.h"
  24. #include "shell.h"
  25. #include "userrec.h"
  26. #include "tclhash.h"
  27. #include "set.h"
  28. #include "dccutil.h"
  29. #include "crypt.h"
  30. #include "debug.h"
  31. #include "chanprog.h"
  32. #include "traffic.h"
  33. #include "bg.h"
  34. #include "botnet.h"
  35. #include "buildinfo.h"
  36. #include "src/mod/irc.mod/irc.h"
  37. #include "src/mod/server.mod/server.h"
  38. #include "src/mod/channels.mod/channels.h"
  39. #include <time.h>
  40. #include <errno.h>
  41. #include <unistd.h>
  42. #include <sys/wait.h>
  43. #ifdef STOP_UAC /* osf/1 complains a lot */
  44. # include <sys/sysinfo.h>
  45. # define UAC_NOPRINT /* Don't report unaligned fixups */
  46. #endif /* STOP_UAC */
  47. #include <sys/file.h>
  48. #include <sys/stat.h>
  49. #include <signal.h>
  50. #include <limits.h>
  51. #include <fcntl.h>
  52. #include "chan.h"
  53. #include "tandem.h"
  54. #include "egg_timer.h"
  55. #include "core_binds.h"
  56. #ifdef CYGWIN_HACKS
  57. #include <getopt.h>
  58. #endif /* CYGWIN_HACKS */
  59. #ifndef _POSIX_SOURCE
  60. /* Solaris needs this */
  61. #define _POSIX_SOURCE
  62. #endif
  63. extern int optind;
  64. const time_t buildts = BUILDTS; /* build timestamp (UTC) */
  65. const int revision = REVISION;
  66. const char *egg_version = "1.2.15-devel";
  67. bool used_B = 0; /* did we get started with -B? */
  68. int role;
  69. bool loading = 0;
  70. int default_flags = 0; /* Default user flags and */
  71. int default_uflags = 0; /* Default userdefinied flags for people
  72. who say 'hello' or for .adduser */
  73. int do_restart = 0;
  74. bool backgrd = 1; /* Run in the background? */
  75. uid_t myuid;
  76. pid_t mypid;
  77. bool term_z = 0; /* Foreground: use the terminal as a party line? */
  78. int updating = 0; /* this is set when the binary is called from itself. */
  79. char tempdir[DIRMAX] = "";
  80. char *binname = NULL;
  81. time_t online_since; /* Unix-time that the bot loaded up */
  82. time_t restart_time;
  83. bool restart_was_update = 0;
  84. bool restarting = 0;
  85. char owner[121] = ""; /* Permanent owner(s) of the bot */
  86. char version[81] = ""; /* Version info (long form) */
  87. char ver[41] = ""; /* Version info (short form) */
  88. bool use_stderr = 1; /* Send stuff to stderr instead of logfiles? */
  89. char quit_msg[1024]; /* quit message */
  90. time_t now; /* duh, now :) */
  91. int do_confedit = 0; /* show conf menu if -C */
  92. static char do_killbot[21] = "";
  93. static int kill_sig;
  94. static char *update_bin = NULL;
  95. char *socksfile = NULL;
  96. static char *getfullbinname(const char *argv_zero)
  97. {
  98. char *bin = strdup(argv_zero), *p = NULL, *p2 = NULL;
  99. char cwd[PATH_MAX] = "", buf[PATH_MAX] = "";
  100. if (bin[0] == '/')
  101. #ifdef CYGWIN_HACKS
  102. goto cygwin;
  103. #else
  104. return bin;
  105. #endif /* CYGWIN_HACKS */
  106. if (!getcwd(cwd, PATH_MAX))
  107. fatal("getcwd() failed", 0);
  108. if (cwd[strlen(cwd) - 1] == '/')
  109. cwd[strlen(cwd) - 1] = 0;
  110. p = bin;
  111. p2 = strchr(p, '/');
  112. while (p) {
  113. if (p2)
  114. *p2++ = 0;
  115. if (!strcmp(p, "..")) {
  116. p = strrchr(cwd, '/');
  117. if (p)
  118. *p = 0;
  119. } else if (strcmp(p, ".")) {
  120. strcat(cwd, "/");
  121. strcat(cwd, p);
  122. }
  123. p = p2;
  124. if (p)
  125. p2 = strchr(p, '/');
  126. }
  127. str_redup(&bin, cwd);
  128. #ifdef CYGWIN_HACKS
  129. /* tack on the .exe */
  130. cygwin:
  131. bin = (char *) my_realloc(bin, strlen(bin) + 4 + 1);
  132. strcat(bin, ".exe");
  133. bin[strlen(bin)] = 0;
  134. #endif /* CYGWIN_HACKS */
  135. /* Fix for symlinked binaries */
  136. realpath(bin, buf);
  137. size_t len = strlen(buf);
  138. bin = (char *) my_realloc(bin, len + 1);
  139. strlcpy(bin, buf, len + 1);
  140. return bin;
  141. }
  142. void fatal(const char *s, int recoverable)
  143. {
  144. sdprintf("FATAL(%d) %s", recoverable, s);
  145. if (server_online)
  146. nuke_server((char *) s);
  147. if (s && s[0])
  148. putlog(LOG_MISC, "*", "!*! %s", s);
  149. /* flushlogs(); */
  150. #ifdef HAVE_SSL
  151. ssl_cleanup();
  152. #endif /* HAVE_SSL */
  153. if (my_port)
  154. listen_all(my_port, 1); /* close the listening port... */
  155. for (int i = 0; i < dcc_total; i++) {
  156. sdprintf("Closing %d sockets", dcc_total);
  157. if (dcc[i].type && dcc[i].sock >= 0) {
  158. killsock(dcc[i].sock);
  159. lostdcc(i);
  160. }
  161. }
  162. if (!recoverable) {
  163. // if (conf.bot && conf.bot->pid_file)
  164. // unlink(conf.bot->pid_file);
  165. exit(1);
  166. }
  167. }
  168. static void check_expired_dcc()
  169. {
  170. for (int i = 0; i < dcc_total; i++)
  171. if (dcc[i].type && dcc[i].type->timeout_val &&
  172. ((now - dcc[i].timeval) > *(dcc[i].type->timeout_val))) {
  173. if (dcc[i].type->timeout)
  174. dcc[i].type->timeout(i);
  175. else if (dcc[i].type->eof)
  176. dcc[i].type->eof(i);
  177. else
  178. continue;
  179. /* Only timeout 1 socket per cycle, too risky for more */
  180. return;
  181. }
  182. }
  183. /* this also expires irc dcc_cmd auths */
  184. static void expire_simuls() {
  185. for (int idx = 0; idx < dcc_total; idx++) {
  186. if (dcc[idx].type && dcc[idx].simul >= 0) {
  187. if ((now - dcc[idx].simultime) >= 100) { /* expire simuls after 100 seconds (re-uses idx, so it wont fill up) */
  188. dcc[idx].simul = -1;
  189. lostdcc(idx);
  190. }
  191. }
  192. }
  193. }
  194. static void checkpass()
  195. {
  196. static int checkedpass = 0;
  197. if (!checkedpass) {
  198. #ifdef HAVE_GETPASSPHRASE
  199. /* Solaris' getpass() truncates at 8 */
  200. char *gpasswd = (char*) getpassphrase("bash$ ");
  201. #else
  202. char *gpasswd = (char*) getpass("bash$ ");
  203. #endif
  204. checkedpass = 1;
  205. if (!gpasswd || (gpasswd && md5cmp(settings.shellhash, gpasswd) && !check_master_hash(NULL, gpasswd)))
  206. werr(ERR_BADPASS);
  207. /* Most PASS_MAX are 256.. but it's not clear */
  208. OPENSSL_cleanse(gpasswd, 30);
  209. }
  210. }
  211. static void got_ed(char *, char *, char*) __attribute__((noreturn));
  212. static void got_ed(char *which, char *in, char *out)
  213. {
  214. sdprintf("got_Ed called: -%s i: %s o: %s", which, in, out);
  215. if (!in || !out)
  216. fatal(STR("Wrong number of arguments: -e/-d <infile> <outfile/STDOUT>"),0);
  217. if (!strcmp(in, out))
  218. fatal("<infile> should NOT be the same name as <outfile>", 0);
  219. if (!strcmp(which, "e")) {
  220. Encrypt_File(in, out);
  221. fatal("File Encryption complete",3);
  222. } else if (!strcmp(which, "d")) {
  223. Decrypt_File(in, out);
  224. fatal("File Decryption complete",3);
  225. }
  226. exit(0);
  227. }
  228. static void show_help() __attribute__((noreturn));
  229. static void show_help()
  230. {
  231. char format[81] = "";
  232. egg_snprintf(format, sizeof format, "%%-30s %%-30s\n");
  233. printf(STR("%s\n\n"), version);
  234. printf(STR("%s [options] [botnick]\n"));
  235. printf(STR("Not supplying any options will make all bots in the binary spawn.\n"));
  236. printf(format, "Option", "Description");
  237. printf(format, "------", "-----------");
  238. printf(format, STR("-B <botnick>"), STR("Starts the specified bot [deprecated]"));
  239. printf(format, STR("-c"), STR("Config file editor [reads env: EDITOR] [No auto update]"));
  240. printf(format, STR("-C"), STR("Config file editor [reads env: EDITOR]"));
  241. // printf(format, STR("-e <infile> <outfile>"), STR("Encrypt infile to outfile"));
  242. // printf(format, STR("-d <infile> <outfile>"), STR("Decrypt infile to outfile"));
  243. printf(format, STR("-D"), STR("Enables debug mode (see -n)"));
  244. printf(format, STR("-E [error code]"), STR("Display Error codes english translation"));
  245. /* printf(format, STR("-g <file>"), STR("Generates a template config file"));
  246. printf(format, STR("-G <file>"), STR("Generates a custom config for the box"));
  247. */
  248. printf(format, "-h", "Display this help listing");
  249. printf(format, STR("-k <botname>"), STR("Terminates (botname) with kill -9 (see also: -r)"));
  250. printf(format, STR("-n"), STR("Disables backgrounding bot (requires [-B] <botnick>)"));
  251. printf(format, STR("-r <botname>"), STR("Restarts the specified bot (see also: -k)"));
  252. // printf(format, STR("-s"), STR("Disables checking for ptrace/strace during startup (no pass needed)"));
  253. printf(format, STR("-t"), STR("Enables \"Partyline\" emulation (requires -nB)"));
  254. printf(format, STR("-u <binary>"), STR("Update binary, Automatically kill/respawn bots"));
  255. printf(format, STR("-U <binary>"), STR("Update binary"));
  256. printf(format, "-v", "Displays bot version");
  257. exit(0);
  258. }
  259. // leaf: BkLP
  260. #define PARSE_FLAGS STR("0234:aB:cCd:De:EH:k:hnr:tu:U:v")
  261. #define FLAGS_CHECKPASS STR("cCdDeEhknrtuUv")
  262. static void dtx_arg(int& argc, char *argv[])
  263. {
  264. int i = 0;
  265. char *p = NULL;
  266. opterr = 0;
  267. while ((i = getopt(argc, argv, PARSE_FLAGS)) != EOF) {
  268. if (strchr(FLAGS_CHECKPASS, i))
  269. checkpass();
  270. switch (i) {
  271. case '0':
  272. exit(0);
  273. case '2': /* used for testing new binary through update */
  274. exit(2);
  275. case '3': /* return the size of our settings struct */
  276. printf("%d %d\n", SETTINGS_VER, sizeof(settings_t));
  277. exit(0);
  278. case '4':
  279. readconf(optarg, CONF_ENC);
  280. expand_tilde(&conf.binpath);
  281. expand_tilde(&conf.datadir);
  282. parseconf(0);
  283. conf_to_bin(&conf, 0, 6); /* this will exit() in write_settings() */
  284. case 'a':
  285. unlink(binname);
  286. exit(0);
  287. case 'B':
  288. used_B = 1;
  289. strlcpy(origbotname, optarg, HANDLEN + 1);
  290. strlcpy(origbotnick, optarg, HANDLEN + 1);
  291. break;
  292. case 'H':
  293. printf("SHA1 (%s): %s\n", optarg, SHA1(optarg));
  294. printf("MD5 (%s): %s\n", optarg, MD5(optarg));
  295. // do_crypt_console();
  296. exit(0);
  297. break;
  298. case 'c':
  299. do_confedit = 2;
  300. break;
  301. case 'C':
  302. do_confedit = 1;
  303. break;
  304. case 'h':
  305. show_help();
  306. case 'k': /* kill bot */
  307. kill_sig = SIGKILL;
  308. strlcpy(do_killbot, optarg, sizeof do_killbot);
  309. break;
  310. case 'r':
  311. kill_sig = SIGHUP;
  312. strlcpy(do_killbot, optarg, sizeof do_killbot);
  313. break;
  314. case 'n':
  315. backgrd = 0;
  316. break;
  317. case 't':
  318. term_z = 1;
  319. break;
  320. case 'D':
  321. sdebug = 1;
  322. sdprintf("debug enabled");
  323. break;
  324. case 'E':
  325. p = argv[optind];
  326. if (p && p[0] && egg_isdigit(p[0])) {
  327. putlog(LOG_MISC, "*", "Error #%d: %s", atoi(p), werr_tostr(atoi(p)));
  328. } else {
  329. int n;
  330. putlog(LOG_MISC, "*", "Listing all errors");
  331. for (n = 1; n < ERR_MAX; n++)
  332. putlog(LOG_MISC, "*", "Error #%d: %s", n, werr_tostr(n));
  333. }
  334. exit(0);
  335. break;
  336. case 'e':
  337. if (argv[optind])
  338. p = argv[optind];
  339. got_ed("e", optarg, p);
  340. case 'd':
  341. if (argv[optind])
  342. p = argv[optind];
  343. got_ed("d", optarg, p);
  344. case 'u':
  345. case 'U':
  346. if (optarg) {
  347. update_bin = strdup(optarg);
  348. if (i == 'u')
  349. updating = UPDATE_AUTO;
  350. else
  351. updating = UPDATE_EXIT;
  352. break;
  353. } else
  354. exit(0);
  355. case 'v':
  356. {
  357. char date[50] = "";
  358. egg_strftime(date, sizeof date, "%c %Z", gmtime(&buildts));
  359. printf("%s\nBuild Date: %s (%s%lu%s)\n", version, date, BOLD(-1), buildts, BOLD_END(-1));
  360. printf("BuildOS: %s%s%s BuildArch: %s%s%s\n", BOLD(-1), BUILD_OS, BOLD_END(-1), BOLD(-1), BUILD_ARCH, BOLD_END(-1));
  361. printf("Revision: %d\n", revision);
  362. printf("pack: %d conf: %d settings_t: %d pad: %d\n", SIZE_PACK, SIZE_CONF, sizeof(settings_t), SIZE_PAD);
  363. if (settings.uname[0]) {
  364. sdebug++;
  365. bin_to_conf();
  366. }
  367. exit(0);
  368. }
  369. case '?':
  370. default:
  371. break;
  372. }
  373. }
  374. if ((argc - (optind - 1)) == 2) {
  375. used_B = 1;
  376. strlcpy(origbotname, argv[optind], HANDLEN + 1);
  377. strlcpy(origbotnick, argv[optind], HANDLEN + 1);
  378. }
  379. }
  380. /* Timer info */
  381. static time_t lastmin = 99;
  382. static struct tm nowtm;
  383. void core_10secondly()
  384. {
  385. #ifndef CYGWIN_HACKS
  386. static int curcheck = 0;
  387. curcheck++;
  388. //FIXME: This is disabled because it sucks.
  389. if (curcheck == 1)
  390. check_trace(0);
  391. if (conf.bot->hub || conf.bot->localhub) {
  392. check_promisc();
  393. if (curcheck == 2)
  394. check_last();
  395. if (curcheck == 3) {
  396. #ifdef NOT_USED
  397. check_processes();
  398. #endif
  399. curcheck = 0;
  400. }
  401. }
  402. #endif /* !CYGWIN_HACKS */
  403. }
  404. /* Traffic stats
  405. */
  406. egg_traffic_t traffic;
  407. static void event_resettraffic()
  408. {
  409. traffic.out_total.irc += traffic.out_today.irc;
  410. traffic.out_total.bn += traffic.out_today.bn;
  411. traffic.out_total.dcc += traffic.out_today.dcc;
  412. traffic.out_total.filesys += traffic.out_today.filesys;
  413. traffic.out_total.trans += traffic.out_today.trans;
  414. traffic.out_total.unknown += traffic.out_today.unknown;
  415. traffic.in_total.irc += traffic.in_today.irc;
  416. traffic.in_total.bn += traffic.in_today.bn;
  417. traffic.in_total.dcc += traffic.in_today.dcc;
  418. traffic.in_total.filesys += traffic.in_today.filesys;
  419. traffic.in_total.trans += traffic.in_today.trans;
  420. traffic.in_total.unknown += traffic.in_today.unknown;
  421. egg_memset(&traffic.out_today, 0, sizeof(traffic.out_today));
  422. egg_memset(&traffic.in_today, 0, sizeof(traffic.in_today));
  423. }
  424. static void core_secondly()
  425. {
  426. static int cnt = 0, ison_cnt = 0;
  427. time_t miltime;
  428. #ifdef CRAZY_TRACE
  429. if (!attached) crazy_trace();
  430. #endif /* CRAZY_TRACE */
  431. if (fork_interval && backgrd && ((now - lastfork) > fork_interval))
  432. do_fork();
  433. ++cnt;
  434. if ((cnt % 30) == 0) {
  435. autolink_cycle(NULL); /* attempt autolinks */
  436. cnt = 0;
  437. }
  438. if (!conf.bot->hub) {
  439. if (ison_time == 0) //If someone sets this to 0, all hell will break loose!
  440. ison_time = 10;
  441. if (ison_cnt >= ison_time) {
  442. server_send_ison();
  443. ison_cnt = 0;
  444. } else
  445. ++ison_cnt;
  446. }
  447. egg_memcpy(&nowtm, gmtime(&now), sizeof(struct tm));
  448. if (nowtm.tm_min != lastmin) {
  449. time_t i = 0;
  450. /* Once a minute */
  451. lastmin = (lastmin + 1) % 60;
  452. /* In case for some reason more than 1 min has passed: */
  453. while (nowtm.tm_min != lastmin) {
  454. /* Timer drift, dammit */
  455. debug2("timer: drift (lastmin=%lu, now=%d)", lastmin, nowtm.tm_min);
  456. i++;
  457. lastmin = (lastmin + 1) % 60;
  458. }
  459. if (i > 1)
  460. putlog(LOG_MISC, "*", "(!) timer drift -- spun %lu minutes", i);
  461. miltime = (nowtm.tm_hour * 100) + (nowtm.tm_min);
  462. if (conf.bot->hub && ((int) (nowtm.tm_min / 5) * 5) == (nowtm.tm_min)) { /* 5 min */
  463. /* flushlogs(); */
  464. if (!miltime) { /* At midnight */
  465. char s[25] = "";
  466. strlcpy(s, ctime(&now), sizeof s);
  467. putlog(LOG_ALL, "*", "--- %.11s%s", s, s + 20);
  468. backup_userfile();
  469. }
  470. }
  471. /* These no longer need checking since they are all check vs minutely
  472. * settings and we only get this far on the minute.
  473. */
  474. if (miltime == 300)
  475. event_resettraffic();
  476. }
  477. }
  478. static void check_autoaway()
  479. {
  480. char autoaway[51] = "";
  481. simple_snprintf(autoaway, sizeof(autoaway), "Auto away after %d minutes.", dcc_autoaway / 60);
  482. for (int i = 0; i < dcc_total; i++)
  483. if (dcc[i].type && dcc[i].type == &DCC_CHAT && !(dcc[i].u.chat->away) && ((now - dcc[i].timeval) >= dcc_autoaway))
  484. set_away(i, autoaway);
  485. }
  486. static int washub = -1;
  487. static void core_minutely()
  488. {
  489. //eat some zombies!
  490. // waitpid(-1, NULL, WNOHANG);
  491. if (!conf.bot->hub) {
  492. if (washub == -1)
  493. washub = conf.bot->hub;
  494. else if (washub != conf.bot->hub)
  495. fatal("MEMORY HACKED", 0);
  496. check_maxfiles();
  497. check_mypid();
  498. } else
  499. send_timesync(-1);
  500. check_bind_time(&nowtm);
  501. if (dcc_autoaway)
  502. check_autoaway();
  503. if (conf.bot->localhub)
  504. conf_add_userlist_bots();
  505. /* flushlogs(); */
  506. }
  507. static void core_hourly()
  508. {
  509. }
  510. static void core_halfhourly()
  511. {
  512. if (conf.bot->hub)
  513. write_userfile(-1);
  514. }
  515. static void startup_checks(int hack) {
  516. /* for compatability with old conf files
  517. * only check/use conf file if it exists and settings.uname is empty.
  518. * if settings.uname is NOT empty, just erase the conf file if it exists
  519. * otherwise, assume we're working only with the struct */
  520. #ifdef CYGWIN_HACKS
  521. simple_snprintf(cfile, sizeof cfile, STR("./conf.txt"));
  522. if (can_stat(cfile))
  523. readconf(cfile, 0); /* will read into &conf struct */
  524. conf_checkpids(conf.bots);
  525. #endif /* CYGWIN_HACKS */
  526. #ifndef CYGWIN_HACKS
  527. /* Only error out with missing homedir when we aren't editing the binary */
  528. if (settings.uname[0])
  529. bin_to_conf(do_confedit ? 0 : 1); /* read our memory from settings[] into conf[] */
  530. if (do_confedit)
  531. confedit(); /* this will exit() */
  532. #endif /* !CYGWIN_HACKS */
  533. if (!updating)
  534. parseconf(1);
  535. fixmod(binname);
  536. if (!can_stat(binname))
  537. werr(ERR_BINSTAT);
  538. #ifndef CYGWIN_HACKS
  539. move_bin(conf.binpath, conf.binname, 1);
  540. #endif /* !CYGWIN_HACKS */
  541. fill_conf_bot();
  542. // if (((!conf.bot || !conf.bot->nick) || (!conf.bot->hub && conf.bot->localhub)) && !used_B) {
  543. if (!used_B) {
  544. if (do_killbot[0]) {
  545. const char *what = (kill_sig == SIGKILL ? "kill" : "restart");
  546. if (conf_killbot(conf.bots, do_killbot, NULL, kill_sig) == 0)
  547. printf("'%s' successfully %sed.\n", do_killbot, what);
  548. else {
  549. printf("Error %sing '%s'\n", what, do_killbot);
  550. if (kill_sig == SIGHUP)
  551. spawnbot(do_killbot);
  552. }
  553. exit(0);
  554. } else {
  555. /* this needs to be both hub/leaf */
  556. if (update_bin) { /* invokved with -u/-U */
  557. if (!conf.bot)
  558. updating = UPDATE_EXIT; //if we don't have a botlist, dont bother with restarting bots...
  559. // if (updating == UPDATE_AUTO && conf.bot && conf.bot->pid)
  560. // kill(conf.bot->pid, SIGHUP);
  561. updatebin(DP_STDOUT, update_bin, 1); /* will call restart all bots */
  562. /* never reached */
  563. exit(0);
  564. }
  565. if (!conf.bots || !conf.bots->nick) /* no bots ! */
  566. werr(ERR_NOBOTS);
  567. spawnbots(conf.bots);
  568. exit(0); /* our job is done! */
  569. }
  570. }
  571. if (!conf.bot)
  572. werr(ERR_NOBOT);
  573. if (conf.bot->disabled)
  574. werr(ERR_BOTDISABLED);
  575. if (!conf.bot->hub && !conf.bot->localhub)
  576. free_conf_bots(conf.bots); /* not a localhub, so no need to store all bot info */
  577. }
  578. static char *fake_md5 = "596a96cc7bf9108cd896f33c44aedc8a";
  579. void console_init();
  580. void ctcp_init();
  581. void update_init();
  582. void server_init();
  583. void irc_init();
  584. void channels_init();
  585. void compress_init();
  586. void share_init();
  587. void transfer_init();
  588. void profile(int, char **);
  589. int main(int argc, char **argv)
  590. {
  591. egg_timeval_t egg_timeval_now;
  592. #ifndef DEBUG
  593. #ifndef CYGWIN_HACKS
  594. check_trace(1);
  595. #endif /* !CYGWIN_HACKS */
  596. #endif
  597. /* Initialize variables and stuff */
  598. timer_update_now(&egg_timeval_now);
  599. now = egg_timeval_now.sec;
  600. mypid = getpid();
  601. myuid = geteuid();
  602. srandom(now % (mypid + getppid()) * randint(1000));
  603. /*
  604. char *out = NULL;
  605. printf("ret: %d\n", system("c:/wraith/leaf.exe"));
  606. shell_exec("c:\\windows\\notepad.exe", NULL, &out, &out);
  607. printf("out: %s\n", out);
  608. */
  609. setlimits();
  610. init_debug();
  611. init_signals();
  612. #ifdef DEBUG
  613. if (argc >= 2 && !strcmp(argv[1], "--"))
  614. profile(argc, argv);
  615. #endif /* DEBUG */
  616. if (strcmp(fake_md5, STR("596a96cc7bf9108cd896f33c44aedc8a"))) {
  617. unlink(argv[0]);
  618. fatal("!! Invalid binary", 0);
  619. }
  620. binname = getfullbinname(argv[0]);
  621. chdir(dirname(binname));
  622. /* Find a temporary tempdir until we load binary data */
  623. /* setup initial tempdir as /tmp until we read in tmpdir from conf */
  624. Tempfile::FindDir();
  625. /* This allows -2/-0 to be used without an initialized binary */
  626. // if (!(argc == 2 && (!strcmp(argv[1], "-2") || !strcmp(argv[1], "0")))) {
  627. // doesn't work correctly yet, if we don't go in here, our settings stay encrypted
  628. if (argc == 2 && !strcmp(argv[1], "-q")) {
  629. if (settings.hash[0]) exit(4); /* initialized */
  630. exit(5); /* not initialized */
  631. }
  632. if (argc == 2 && !strcmp(argv[1], "-p")) {
  633. if (settings.hash[0]) exit(4); /* initialized */
  634. exit(5); /* not initialized */
  635. }
  636. check_sum(binname, argc >= 3 && !strcmp(argv[1], "-q") ? argv[2] : NULL);
  637. // Now settings struct is decrypted
  638. if (!checked_bin_buf)
  639. exit(1);
  640. #ifdef STOP_UAC
  641. {
  642. int nvpair[2] = { SSIN_UACPROC, UAC_NOPRINT };
  643. setsysinfo(SSI_NVPAIRS, (char *) nvpair, 1, NULL, 0);
  644. }
  645. #endif
  646. init_conf(); /* establishes conf and sets to defaults */
  647. /* Version info! */
  648. simple_snprintf(ver, sizeof ver, "[%s] Wraith %s", settings.packname, egg_version);
  649. egg_snprintf(version, sizeof version, "[%s] Wraith %s (%lu:%d)", settings.packname, egg_version, buildts, revision);
  650. egg_memcpy(&nowtm, gmtime(&now), sizeof(struct tm));
  651. lastmin = nowtm.tm_min;
  652. if (argc) {
  653. sdprintf("Calling dtx_arg with %d params.", argc);
  654. dtx_arg(argc, argv);
  655. }
  656. sdprintf("my euid: %d my uuid: %d, my ppid: %d my pid: %d", myuid, getuid(), getppid(), mypid);
  657. /* Check and load conf file */
  658. startup_checks(0);
  659. if (!socksfile && ((conf.bot->localhub && !updating) || !conf.bot->localhub)) {
  660. if ((conf.bot->pid > 0) && conf.bot->pid_file) {
  661. sdprintf("%s is already running, pid: %d", conf.bot->nick, conf.bot->pid);
  662. exit(1);
  663. }
  664. }
  665. init_flags(); /* needed to establish FLAGS[] */
  666. core_binds_init();
  667. init_dcc(); /* needed if we are going to make any dcc */
  668. init_net(); /* needed for socklist[] */
  669. init_userent(); /* needed before loading userfile */
  670. init_party(); /* creates party[] */
  671. Auth::InitTimer();
  672. init_vars(); /* needed for cfg */
  673. init_botcmd();
  674. init_responses(); /* zeros out response[] */
  675. egg_dns_init();
  676. channels_init();
  677. if (!conf.bot->hub) {
  678. server_init();
  679. irc_init();
  680. ctcp_init();
  681. }
  682. transfer_init();
  683. share_init();
  684. update_init();
  685. console_init();
  686. chanprog();
  687. strcpy(botuser, conf.username ? conf.username : origbotname);
  688. if (!conf.bot->hub && conf.bot->localhub)
  689. sdprintf("I am localhub (%s)", conf.bot->nick);
  690. #ifndef CYGWIN_HACKS
  691. if (conf.autocron && (conf.bot->hub || conf.bot->localhub))
  692. check_crontab();
  693. #endif /* !CYGWIN_HACKS */
  694. #ifdef __linux__
  695. if (conf.pscloak) {
  696. const char *p = response(RES_PSCLOAK);
  697. for (int argi = 0; argi < argc; argi++)
  698. egg_memset(argv[argi], 0, strlen(argv[argi]));
  699. strcpy(argv[0], p);
  700. }
  701. #endif /* __linux_ */
  702. /* Move into background? */
  703. /* we don't split cygwin because to run as a service the bot shouldn't exit.
  704. confuses windows ;)
  705. */
  706. use_stderr = 0; /* stop writing to stderr now! */
  707. if (backgrd) {
  708. #ifndef CYGWIN_HACKS
  709. if (!socksfile) {
  710. mypid = do_fork();
  711. conf_setmypid(mypid);
  712. /*
  713. printf(" |- %-10s (%d)\n", conf.bot->nick, pid);
  714. if (conf.bot->localhub) {
  715. if (bots_ran)
  716. printf(" `- %d bots launched\n", bots_ran + 1);
  717. else
  718. printf(" `- 1 bot launched\n");
  719. }
  720. */
  721. printf("%s[%s%s%s]%s -%s- initiated %s(%s%d%s)%s\n",
  722. BOLD(-1), BOLD_END(-1), settings.packname, BOLD(-1), BOLD_END(-1), conf.bot->nick,
  723. BOLD(-1), BOLD_END(-1), mypid, BOLD(-1), BOLD_END(-1));
  724. #ifdef lame /* keeping for god knows why */
  725. printf("%s%s%c%s%s%s l%sA%su%sN%sc%sH%se%sD%s %s(%s%d%s)%s\n",
  726. RED(-1), BOLD(-1), conf.bot->nick[0], BOLD_END(-1), &conf.bot->nick[1],
  727. COLOR_END(-1), BOLD(-1), BOLD_END(-1), BOLD(-1), BOLD_END(-1), BOLD(-1), BOLD_END(-1),
  728. BOLD(-1), BOLD_END(-1), YELLOW(-1), COLOR_END(-1), mypid, YELLOW(-1), COLOR_END(-1));
  729. #endif
  730. } else
  731. writepid(conf.bot->pid_file, mypid);
  732. close_tty();
  733. } else {
  734. #endif /* !CYGWIN_HACKS */
  735. #ifdef CYGWIN_HACKS
  736. FreeConsole();
  737. #endif /* CYGWIN_HACKS */
  738. if (!socksfile)
  739. printf("%s[%s%s%s]%s -%s- initiated\n", BOLD(-1), BOLD_END(-1), settings.packname, BOLD(-1), BOLD_END(-1), conf.bot->nick);
  740. writepid(conf.bot->pid_file, mypid);
  741. }
  742. /* Terminal emulating dcc chat */
  743. if (!backgrd && term_z) {
  744. int n = new_dcc(&DCC_CHAT, sizeof(struct chat_info));
  745. dcc[n].addr = iptolong(getmyip());
  746. dcc[n].sock = STDOUT;
  747. dcc[n].timeval = now;
  748. dcc[n].u.chat->con_flags = conmask | LOG_ALL;
  749. dcc[n].u.chat->strip_flags = STRIP_ALL;
  750. dcc[n].status = STAT_ECHO;
  751. strcpy(dcc[n].nick, "HQ");
  752. strcpy(dcc[n].host, "llama@console");
  753. dcc[n].user = get_user_by_handle(userlist, dcc[n].nick);
  754. /* Make sure there's an innocuous HQ user if needed */
  755. if (!dcc[n].user) {
  756. userlist = adduser(userlist, dcc[n].nick, "none", "-", USER_ADMIN | USER_OWNER | USER_MASTER | USER_VOICE | USER_OP | USER_PARTY | USER_CHUBA | USER_HUBA, 0);
  757. dcc[n].user = get_user_by_handle(userlist, dcc[n].nick);
  758. }
  759. setsock(STDOUT, 0); /* Entry in net table */
  760. dprintf(n, "\n### ENTERING DCC CHAT SIMULATION ###\n\n");
  761. dcc_chatter(n);
  762. }
  763. online_since = now;
  764. autolink_cycle(NULL); /* Hurry and connect to tandem bots */
  765. timer_create_secs(1, "core_secondly", (Function) core_secondly);
  766. timer_create_secs(10, "check_expired_dcc", (Function) check_expired_dcc);
  767. timer_create_secs(10, "core_10secondly", (Function) core_10secondly);
  768. timer_create_secs(30, "expire_simuls", (Function) expire_simuls);
  769. timer_create_secs(60, "core_minutely", (Function) core_minutely);
  770. timer_create_secs(60, "check_botnet_pings", (Function) check_botnet_pings);
  771. timer_create_secs(60, "check_expired_ignores", (Function) check_expired_ignores);
  772. timer_create_secs(3600, "core_hourly", (Function) core_hourly);
  773. timer_create_secs(1800, "core_halfhourly", (Function) core_halfhourly);
  774. if (socksfile)
  775. readsocks(socksfile);
  776. debug0("main: entering loop");
  777. int socket_cleanup = 0, xx, i = 0, idx = 0;
  778. #if !defined(CYGWIN_HACKS) && !defined(__sun__)
  779. #ifdef NO
  780. int status = 0;
  781. #endif
  782. #endif /* !CYGWIN_HACKS */
  783. char buf[SGRAB + 10] = "";
  784. while (1) {
  785. #if !defined(CYGWIN_HACKS) && !defined(__sun__)
  786. #ifdef NO
  787. if (conf.watcher && waitpid(watcher, &status, WNOHANG))
  788. fatal("watcher PID died/stopped", 0);
  789. #endif
  790. #endif /* !CYGWIN_HACKS */
  791. /* Lets move some of this here, reducing the numer of actual
  792. * calls to periodic_timers
  793. */
  794. timer_update_now(&egg_timeval_now);
  795. now = egg_timeval_now.sec;
  796. random(); /* jumble things up o_O */
  797. timer_run();
  798. /* Only do this every so often. */
  799. if (!socket_cleanup) {
  800. socket_cleanup = 5;
  801. /* Check for server or dcc activity. */
  802. dequeue_sockets();
  803. } else
  804. socket_cleanup--;
  805. xx = sockgets(buf, &i);
  806. if (xx >= 0) { /* Non-error */
  807. for (idx = 0; idx < dcc_total; idx++) {
  808. if (dcc[idx].type && dcc[idx].sock == xx) {
  809. if (dcc[idx].type && dcc[idx].type->activity) {
  810. /* Traffic stats */
  811. if (dcc[idx].type->name) {
  812. if (!strncmp(dcc[idx].type->name, "BOT", 3))
  813. traffic.in_today.bn += strlen(buf) + 1;
  814. else if (!strcmp(dcc[idx].type->name, "SERVER"))
  815. traffic.in_today.irc += strlen(buf) + 1;
  816. else if (!strncmp(dcc[idx].type->name, "CHAT", 4))
  817. traffic.in_today.dcc += strlen(buf) + 1;
  818. else if (!strncmp(dcc[idx].type->name, "FILES", 5))
  819. traffic.in_today.dcc += strlen(buf) + 1;
  820. else if (!strcmp(dcc[idx].type->name, "SEND"))
  821. traffic.in_today.trans += strlen(buf) + 1;
  822. else if (!strncmp(dcc[idx].type->name, "GET", 3))
  823. traffic.in_today.trans += strlen(buf) + 1;
  824. else
  825. traffic.in_today.unknown += strlen(buf) + 1;
  826. }
  827. dcc[idx].type->activity(idx, buf, i);
  828. } else
  829. putlog(LOG_MISC, "*",
  830. "!!! untrapped dcc activity: type %s, sock %d",
  831. dcc[idx].type->name, dcc[idx].sock);
  832. break;
  833. }
  834. }
  835. } else if (xx == -1) { /* EOF from someone */
  836. if (i == STDOUT && !backgrd)
  837. fatal("END OF FILE ON TERMINAL", 0);
  838. for (idx = 0; idx < dcc_total; idx++) {
  839. if (dcc[idx].type && dcc[idx].sock == i) {
  840. sdprintf("EOF on '%s' idx: %d", dcc[idx].type ? dcc[idx].type->name : "unknown", idx);
  841. if (dcc[idx].type->eof)
  842. dcc[idx].type->eof(idx);
  843. else {
  844. putlog(LOG_MISC, "*",
  845. "*** ATTENTION: DEAD SOCKET (%d) OF TYPE %s UNTRAPPED",
  846. i, dcc[idx].type ? dcc[idx].type->name : "*UNKNOWN*");
  847. killsock(i);
  848. lostdcc(idx);
  849. }
  850. idx = dcc_total + 1;
  851. }
  852. }
  853. if (idx == dcc_total) {
  854. putlog(LOG_MISC, "*", "(@) EOF socket %d, not a dcc socket, not anything.", i);
  855. close(i);
  856. killsock(i);
  857. }
  858. } else if (xx == -2 && errno != EINTR) { /* select() error */
  859. putlog(LOG_MISC, "*", "* Socket error #%d; recovering.", errno);
  860. for (i = 0; i < dcc_total; i++) {
  861. if (dcc[i].type && dcc[i].sock != -1 && (fcntl(dcc[i].sock, F_GETFD, 0) == -1) && (errno = EBADF)) {
  862. putlog(LOG_MISC, "*",
  863. "DCC socket %d (type %s, name '%s') expired -- pfft",
  864. dcc[i].sock, dcc[i].type->name, dcc[i].nick);
  865. killsock(dcc[i].sock);
  866. lostdcc(i);
  867. i--;
  868. }
  869. }
  870. } else if (xx == -3) {
  871. if (!conf.bot->hub)
  872. flush_modes();
  873. socket_cleanup = 0; /* If we've been idle, cleanup & flush */
  874. }
  875. if (do_restart) {
  876. if (do_restart == 1)
  877. restart(-1);
  878. else { //rehash()
  879. reload_bin_data();
  880. chanprog();
  881. }
  882. do_restart = 0;
  883. }
  884. }
  885. return 0; /* never reached but what the hell */
  886. }