main.c 27 KB

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