main.cc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. /*
  2. * Copyright (C) 1997 Robey Pointer
  3. * Copyright (C) 1999 - 2002 Eggheads Development Team
  4. * Copyright (C) 2002 - 2014 Bryan Drewery
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. */
  20. /*
  21. * main.c -- handles:
  22. * core event handling
  23. * command line arguments
  24. * context and assert debugging
  25. *
  26. */
  27. #include "common.h"
  28. #include "main.h"
  29. #include "userent.h"
  30. #include "auth.h"
  31. #include "adns.h"
  32. #include "botcmd.h"
  33. #include "color.h"
  34. #include "dcc.h"
  35. #include "misc.h"
  36. #include "binary.h"
  37. #include "response.h"
  38. #include "settings.h"
  39. #include "misc_file.h"
  40. #include "net.h"
  41. #include "users.h"
  42. #include "shell.h"
  43. #include "userrec.h"
  44. #include "binds.h"
  45. #include "set.h"
  46. #include "dccutil.h"
  47. #include "crypt.h"
  48. #include "debug.h"
  49. #include "chanprog.h"
  50. #include "traffic.h"
  51. #include "bg.h"
  52. #include "botnet.h"
  53. #include "buildinfo.h"
  54. #include "src/mod/irc.mod/irc.h"
  55. #include "src/mod/server.mod/server.h"
  56. #include "src/mod/channels.mod/channels.h"
  57. #include <time.h>
  58. #include <errno.h>
  59. #include <unistd.h>
  60. #include <sys/wait.h>
  61. #ifdef STOP_UAC /* osf/1 complains a lot */
  62. # include <sys/sysinfo.h>
  63. # define UAC_NOPRINT /* Don't report unaligned fixups */
  64. #endif /* STOP_UAC */
  65. #include <sys/file.h>
  66. #include <sys/stat.h>
  67. #include <signal.h>
  68. #include <limits.h>
  69. #include <fcntl.h>
  70. #include "chan.h"
  71. #include "tandem.h"
  72. #include "egg_timer.h"
  73. #include "core_binds.h"
  74. #ifndef _POSIX_SOURCE
  75. /* Solaris needs this */
  76. #define _POSIX_SOURCE
  77. #endif
  78. extern int optind;
  79. #if (BUILDTS + 0)
  80. const time_t buildts = BUILDTS; /* build timestamp (UTC) */
  81. const char *commit = COMMIT;
  82. const char *branch = BRANCH;
  83. #else
  84. #error BUILDTS unable to be determined. Gmake required. Source may also be incorrect.
  85. #endif
  86. const char *egg_version = VERSION;
  87. char git_version[50] = "";
  88. bool used_B = 0; /* did we get started with -B? */
  89. bool safe_to_log = 0;
  90. bool loading = 0;
  91. int default_flags = 0; /* Default user flags and */
  92. bool have_linked_to_hub = 0; /* Have we ever been linked to a hub? */
  93. int default_uflags = 0; /* Default userdefinied flags for people
  94. who say 'hello' or for .adduser */
  95. int do_restart = 0;
  96. int do_write_userfile = 0;
  97. bool backgrd = 1; /* Run in the background? */
  98. uid_t myuid;
  99. pid_t mypid;
  100. bool term_z = 0; /* Foreground: use the terminal as a party line? */
  101. int updating = 0; /* this is set when the binary is called from itself. */
  102. char tempdir[PATH_MAX] = "";
  103. char *binname = NULL;
  104. time_t online_since; /* Unix-time that the bot loaded up */
  105. time_t restart_time;
  106. bool restart_was_update = 0;
  107. bool restarting = 0;
  108. char owner[121] = ""; /* Permanent owner(s) of the bot */
  109. char version[151] = ""; /* Version info (long form) */
  110. char ver[101] = ""; /* Version info (short form) */
  111. bool use_stderr = 1; /* Send stuff to stderr instead of logfiles? */
  112. char quit_msg[1024]; /* quit message */
  113. time_t now; /* duh, now :) */
  114. egg_timeval_t egg_timeval_now;
  115. int do_confedit = 0; /* show conf menu if -C */
  116. static char do_killbot[21] = "";
  117. static int kill_sig;
  118. static char *update_bin = NULL;
  119. char *socksfile = NULL;
  120. static char *getfullbinname(const char *argv_zero)
  121. {
  122. char *bin = strdup(argv_zero), *p = NULL, *p2 = NULL;
  123. char cwd[PATH_MAX] = "", buf[PATH_MAX] = "";
  124. if (bin[0] == '/')
  125. goto have_cwd;
  126. if (!getcwd(cwd, PATH_MAX))
  127. fatal(STR("getcwd() failed"), 0);
  128. if (cwd[0] && cwd[strlen(cwd) - 1] == '/')
  129. cwd[strlen(cwd) - 1] = 0;
  130. p = bin;
  131. p2 = strchr(p, '/');
  132. while (p) {
  133. if (p2)
  134. *p2++ = 0;
  135. if (!strcmp(p, "..")) {
  136. p = strrchr(cwd, '/');
  137. if (p)
  138. *p = 0;
  139. } else if (strcmp(p, ".")) {
  140. strlcat(cwd, "/", sizeof(cwd));
  141. strlcat(cwd, p, sizeof(cwd));
  142. }
  143. p = p2;
  144. if (p)
  145. p2 = strchr(p, '/');
  146. }
  147. str_redup(&bin, cwd);
  148. have_cwd:
  149. /* Fix for symlinked binaries */
  150. if (!realpath(bin, buf))
  151. fatal(STR("realpath() failed on getting current working directory."), 0);
  152. size_t len = strlen(buf);
  153. bin = (char *) realloc(bin, len + 1);
  154. strlcpy(bin, buf, len + 1);
  155. return bin;
  156. }
  157. void fatal(const char *s, int recoverable)
  158. {
  159. sdprintf(STR("FATAL(%d) %s"), recoverable, s);
  160. if (server_online)
  161. nuke_server((char *) s);
  162. if (s && s[0])
  163. putlog(LOG_MISC, "*", STR("!*! %s"), s);
  164. /* flushlogs(); */
  165. if (my_port)
  166. listen_all(my_port, 1, 1); /* close the listening port... */
  167. if (conf.bot && conf.bot->localhub)
  168. unlink(conf.localhub_socket);
  169. sdprintf(STR("Closing %d sockets"), dcc_total);
  170. for (int i = 0; i < dcc_total; i++) {
  171. if (!backgrd && i == STDOUT) continue;
  172. if (dcc[i].type && dcc[i].sock >= 0) {
  173. sdprintf(STR("Closing %s dcc(%d)"), dcc[i].type->name, i);
  174. killsock(dcc[i].sock);
  175. lostdcc(i);
  176. }
  177. }
  178. if (!recoverable) {
  179. // uninit_openssl();
  180. // if (conf.bot && conf.bot->pid_file)
  181. // unlink(conf.bot->pid_file);
  182. exit(1);
  183. } else {
  184. ContextNote(__func__, s);
  185. }
  186. }
  187. static void check_expired_dcc()
  188. {
  189. for (int i = 0; i < dcc_total; i++)
  190. if (dcc[i].type && dcc[i].type->timeout_val &&
  191. ((now - dcc[i].timeval) > *(dcc[i].type->timeout_val))) {
  192. if (dcc[i].type->timeout)
  193. dcc[i].type->timeout(i);
  194. else if (dcc[i].type->eof)
  195. dcc[i].type->eof(i);
  196. else
  197. continue;
  198. /* Only timeout 1 socket per cycle, too risky for more */
  199. return;
  200. }
  201. }
  202. /* this also expires irc dcc_cmd auths */
  203. static void expire_simuls() {
  204. for (int idx = 0; idx < dcc_total; idx++) {
  205. if (dcc[idx].type && dcc[idx].simul >= 0) {
  206. if ((now - dcc[idx].simultime) >= 100) { /* expire simuls after 100 seconds (re-uses idx, so it wont fill up) */
  207. dcc[idx].simul = -1;
  208. lostdcc(idx);
  209. }
  210. }
  211. }
  212. }
  213. static int checkedpass = 1;
  214. static void checkpass()
  215. {
  216. int (*hash_cmp) (const char *, const char *) = NULL;
  217. size_t hashlen = strlen(settings.shellhash);
  218. if (hashlen == 32)
  219. hash_cmp = md5cmp;
  220. else if (hashlen == 40)
  221. hash_cmp = sha1cmp;
  222. else if (hashlen == 47)
  223. hash_cmp = salted_sha1cmp;
  224. #define SHELL_PROMPT STR("Enter your binary password: ")
  225. #ifdef HAVE_GETPASSPHRASE
  226. /* Solaris' getpass() truncates at 8 */
  227. char *gpasswd = (char*) getpassphrase(SHELL_PROMPT);
  228. #else
  229. char *gpasswd = (char*) getpass(SHELL_PROMPT);
  230. #endif
  231. if (gpasswd) {
  232. checkedpass = hash_cmp(settings.shellhash, gpasswd);
  233. /* Most PASS_MAX are 256.. but it's not clear */
  234. OPENSSL_cleanse(gpasswd, 30);
  235. }
  236. if (checkedpass) {
  237. OPENSSL_cleanse(&settings, sizeof(settings_t));
  238. CLEAR_SALTS;
  239. }
  240. }
  241. static void got_ed(const char *, const char *, const char*) __attribute__((noreturn));
  242. static void got_ed(const char *which, const char *in, const char *out)
  243. {
  244. sdprintf(STR("got_Ed called: -%s i: %s o: %s"), which, in, out);
  245. if (!in || !out)
  246. fatal(STR("Wrong number of arguments: -e/-d <infile> <outfile>"),0);
  247. if (!strcmp(in, out))
  248. fatal(STR("<infile> should NOT be the same name as <outfile>"), 0);
  249. if (!strcmp(which, "e")) {
  250. Encrypt_File(in, out);
  251. fatal(STR("File Encryption complete"),3);
  252. } else if (!strcmp(which, "d")) {
  253. Decrypt_File(in, out);
  254. fatal(STR("File Decryption complete"),3);
  255. }
  256. exit(0);
  257. }
  258. static void show_help() __attribute__((noreturn));
  259. static void show_help()
  260. {
  261. const char format[] = "%-30s %-30s\n";
  262. printf(STR("%s\n\n"), version);
  263. printf(STR("%s [options] [botnick[.conf]]\n"), binname);
  264. printf(STR("Not supplying any options will make all bots in the binary spawn.\n"));
  265. printf(STR("\n"));
  266. printf(STR("- http://wraith.botpack.net -\n"));
  267. printf(STR("\n"));
  268. printf(format, STR("Option"), STR("Description"));
  269. printf(format, STR("------"), STR("-----------"));
  270. printf(format, STR("[-B] <botnick>"), STR("Starts the specified bot [deprecated]"));
  271. printf(format, STR("-C"), STR("Config file editor [reads env: EDITOR]"));
  272. // printf(format, STR("-e <infile> <outfile>"), STR("Encrypt infile to outfile"));
  273. // printf(format, STR("-d <infile> <outfile>"), STR("Decrypt infile to outfile"));
  274. printf(format, STR("-D"), STR("Enables debug mode (see -n)"));
  275. printf(format, STR("-E [error code]"), STR("Display Error codes english translation"));
  276. /* printf(format, STR("-g <file>"), STR("Generates a template config file"));
  277. printf(format, STR("-G <file>"), STR("Generates a custom config for the box"));
  278. */
  279. printf(format, STR("-h"), STR("Display this help listing"));
  280. printf(format, STR("-k <botname>"), STR("Terminates (botname) with kill -9 (see also: -r)"));
  281. printf(format, STR("-m"), STR("Config file editor [reads env: EDITOR] [No auto update]"));
  282. printf(format, STR("-n"), STR("Disables backgrounding bot (requires [-B] <botnick>)"));
  283. printf(format, STR("-q <pack.cfg>"), STR("Initialize the binary with the given pack.cfg (Can only be done once per binary)"));
  284. printf(format, STR("-Q"), STR("Securely initialize the binary by reading the PackConfig from stdin (paste). (Can only be done once per binary)"));
  285. printf(format, STR("-r <botname>"), STR("Restarts the specified bot (see also: -k)"));
  286. // printf(format, STR("-s"), STR("Disables checking for ptrace/strace during startup (no pass needed)"));
  287. printf(format, STR("-t"), STR("Enables \"Partyline\" emulation (requires -nB)"));
  288. printf(format, STR("-u <binary>"), STR("Update binary, Automatically kill/respawn bots"));
  289. printf(format, STR("-U <binary>"), STR("Update binary"));
  290. printf(format, STR("-v"), STR("Displays bot version"));
  291. printf(format, STR("-V"), STR("Displays the pack.cfg being used"));
  292. exit(0);
  293. }
  294. // leaf: BkLP
  295. #define PARSE_FLAGS STR("0234:aB:cCd:De:EH:k:hmnr:tu:U:vV")
  296. #define FLAGS_CHECKPASS STR("cCdDeEkmnrtuUV")
  297. static void dtx_arg(int& argc, char *argv[])
  298. {
  299. int i = 0, checked_pass = 0;
  300. char *p = NULL;
  301. #ifdef DEBUG
  302. checked_pass = 1;
  303. #endif
  304. opterr = 0;
  305. while ((i = getopt(argc, argv, PARSE_FLAGS)) != EOF) {
  306. if (strchr(FLAGS_CHECKPASS, i) && !checked_pass) {
  307. checkpass();
  308. ++checked_pass;
  309. }
  310. switch (i) {
  311. case '0':
  312. exit(0);
  313. case '2': /* used for testing new binary through update */
  314. exit(2);
  315. case '4':
  316. readconf(optarg, CONF_ENC);
  317. expand_tilde(&conf.datadir);
  318. parseconf(0);
  319. conf_to_bin(&conf, 0, 6); /* this will exit() in write_settings() */
  320. case 'a':
  321. unlink(binname);
  322. exit(0);
  323. case 'B':
  324. used_B = 1;
  325. strlcpy(origbotname, optarg, sizeof(origbotname));
  326. strlcpy(origbotnick, optarg, sizeof(origbotnick));
  327. break;
  328. case 'H':
  329. printf("SHA1 (%s): %s\n", optarg, SHA1(optarg));
  330. printf("MD5 (%s): %s\n", optarg, MD5(optarg));
  331. // do_crypt_console();
  332. exit(0);
  333. break;
  334. case 'm':
  335. do_confedit = 2;
  336. break;
  337. case 'c':
  338. case 'C':
  339. do_confedit = 1;
  340. break;
  341. case 'h':
  342. show_help();
  343. case 'k': /* kill bot */
  344. kill_sig = SIGKILL;
  345. strlcpy(do_killbot, optarg, sizeof do_killbot);
  346. break;
  347. case 'r':
  348. kill_sig = SIGHUP;
  349. strlcpy(do_killbot, optarg, sizeof do_killbot);
  350. break;
  351. case 'n':
  352. backgrd = 0;
  353. break;
  354. case 't':
  355. term_z = 1;
  356. break;
  357. case 'D':
  358. sdebug = 1;
  359. sdprintf("debug enabled");
  360. break;
  361. case 'E':
  362. p = argv[optind];
  363. if (p && p[0] && egg_isdigit(p[0])) {
  364. putlog(LOG_MISC, "*", STR("Error #%d: %s"), atoi(p), werr_tostr(atoi(p)));
  365. } else {
  366. int n;
  367. putlog(LOG_MISC, "*", STR("Listing all errors"));
  368. for (n = 1; n < ERR_MAX; n++)
  369. putlog(LOG_MISC, "*", STR("Error #%d: %s"), n, werr_tostr(n));
  370. }
  371. exit(0);
  372. break;
  373. case 'e':
  374. if (argv[optind])
  375. p = argv[optind];
  376. got_ed("e", optarg, p);
  377. case 'd':
  378. if (argv[optind])
  379. p = argv[optind];
  380. got_ed("d", optarg, p);
  381. case 'u':
  382. case 'U':
  383. if (optarg) {
  384. update_bin = strdup(optarg);
  385. if (i == 'u')
  386. updating = UPDATE_AUTO;
  387. else
  388. updating = UPDATE_EXIT;
  389. break;
  390. } else
  391. exit(0);
  392. case 'v':
  393. {
  394. char date[50] = "";
  395. strftime(date, sizeof date, "%c %Z", gmtime(&buildts));
  396. printf(STR("%s\nBuild Date: %s (%s%li%s)\n"), version, date, BOLD(-1), (long)buildts, BOLD_END(-1));
  397. printf(STR("BuildOS: %s%s%s BuildArch: %s%s%s\n"), BOLD(-1), BUILD_OS, BOLD_END(-1), BOLD(-1), BUILD_ARCH, BOLD_END(-1));
  398. printf(STR("- http://wraith.botpack.net -\n"));
  399. #ifdef DEBUG
  400. printf(STR("pack: %zu conf: %zu settings_t: %zu prefix: %zu pad: %zu/%zu needed padding: %zu/%zu\n"),
  401. SIZE_PACK,
  402. SIZE_CONF,
  403. SIZE_SETTINGS,
  404. PREFIXLEN,
  405. SIZE_PAD_PACK,
  406. SIZE_PAD,
  407. (SIZE_PAD_ALIGN - ((SIZE_PACK - SIZE_PAD_PACK) % SIZE_PAD_ALIGN)) % SIZE_PAD_ALIGN,
  408. (SIZE_PAD_ALIGN - ((SIZE_SETTINGS - SIZE_PAD) % SIZE_PAD_ALIGN)) % SIZE_PAD_ALIGN
  409. );
  410. #endif
  411. if (settings.dynamic_initialized[0]) {
  412. bin_to_conf();
  413. }
  414. exit(0);
  415. }
  416. case 'V':
  417. writecfg();
  418. exit(0);
  419. break;
  420. case '?':
  421. default:
  422. break;
  423. }
  424. }
  425. if ((argc - (optind - 1)) == 2) {
  426. used_B = 1;
  427. strlcpy(origbotname, argv[optind], sizeof(origbotname));
  428. strlcpy(origbotnick, argv[optind], sizeof(origbotnick));
  429. /* Trim off .conf */
  430. p = strchr(origbotname, '.');
  431. if (p) {
  432. origbotname[(p - origbotname)] = 0;
  433. origbotnick[(p - origbotname)] = 0;
  434. }
  435. }
  436. }
  437. /* Timer info */
  438. static int lastmin = 99;
  439. static struct tm nowtm;
  440. void core_10secondly()
  441. {
  442. static int curcheck = 0;
  443. ++curcheck;
  444. //FIXME: This is disabled because it sucks.
  445. if (curcheck == 1)
  446. check_trace(0);
  447. if (conf.bot->hub || conf.bot->localhub) {
  448. if (tands > 0) {
  449. check_promisc();
  450. if (curcheck == 2)
  451. check_last();
  452. }
  453. if (curcheck == 3)
  454. curcheck = 0;
  455. }
  456. }
  457. /* Traffic stats
  458. */
  459. egg_traffic_t traffic;
  460. static void event_resettraffic()
  461. {
  462. traffic.out_total.irc += traffic.out_today.irc;
  463. traffic.out_total.bn += traffic.out_today.bn;
  464. traffic.out_total.dcc += traffic.out_today.dcc;
  465. traffic.out_total.filesys += traffic.out_today.filesys;
  466. traffic.out_total.trans += traffic.out_today.trans;
  467. traffic.out_total.unknown += traffic.out_today.unknown;
  468. traffic.in_total.irc += traffic.in_today.irc;
  469. traffic.in_total.bn += traffic.in_today.bn;
  470. traffic.in_total.dcc += traffic.in_today.dcc;
  471. traffic.in_total.filesys += traffic.in_today.filesys;
  472. traffic.in_total.trans += traffic.in_today.trans;
  473. traffic.in_total.unknown += traffic.in_today.unknown;
  474. memset(&traffic.out_today, 0, sizeof(traffic.out_today));
  475. memset(&traffic.in_today, 0, sizeof(traffic.in_today));
  476. }
  477. static void core_secondly()
  478. {
  479. static int cnt = 0;
  480. time_t miltime;
  481. ++cnt;
  482. if (((conf.bot->localhub || conf.bot->hub) && (cnt % 30) == 0) || (cnt % 5) == 0) {
  483. autolink_cycle(); /* attempt autolinks */
  484. cnt = 0;
  485. }
  486. if (unlikely(do_write_userfile) && do_write_userfile-- == 1) {
  487. real_write_userfile(-1);
  488. }
  489. memcpy(&nowtm, gmtime(&now), sizeof(struct tm));
  490. if (nowtm.tm_min != lastmin) {
  491. int i = 0;
  492. /* Once a minute */
  493. lastmin = (lastmin + 1) % 60;
  494. /* In case for some reason more than 1 min has passed: */
  495. while (nowtm.tm_min != lastmin) {
  496. /* Timer drift, dammit */
  497. debug2("timer: drift (lastmin=%d, now=%d)", lastmin, nowtm.tm_min);
  498. ++i;
  499. lastmin = (lastmin + 1) % 60;
  500. }
  501. if (i > 1)
  502. putlog(LOG_MISC, "*", "(!) timer drift -- spun %d minutes", i);
  503. miltime = (nowtm.tm_hour * 100) + (nowtm.tm_min);
  504. if (conf.bot->hub && ((int) (nowtm.tm_min / 5) * 5) == (nowtm.tm_min)) { /* 5 min */
  505. /* flushlogs(); */
  506. if (!miltime) { /* At midnight */
  507. char s[25] = "";
  508. strlcpy(s, ctime(&now), sizeof s);
  509. putlog(LOG_ALL, "*", "--- %.11s%s", s, s + 20);
  510. backup_userfile();
  511. }
  512. }
  513. /* These no longer need checking since they are all check vs minutely
  514. * settings and we only get this far on the minute.
  515. */
  516. if (miltime == 300)
  517. event_resettraffic();
  518. }
  519. }
  520. static void check_autoaway()
  521. {
  522. char autoaway[51] = "";
  523. simple_snprintf(autoaway, sizeof(autoaway), "Auto away after %d minutes.", dcc_autoaway / 60);
  524. for (int i = 0; i < dcc_total; i++)
  525. if (dcc[i].type && dcc[i].type == &DCC_CHAT && !(dcc[i].u.chat->away) && ((now - dcc[i].timeval) >= dcc_autoaway))
  526. set_away(i, autoaway);
  527. }
  528. static int washub = -1;
  529. static void core_minutely()
  530. {
  531. //eat some zombies!
  532. // waitpid(-1, NULL, WNOHANG);
  533. if (!conf.bot->hub) {
  534. if (washub == -1)
  535. washub = conf.bot->hub;
  536. else if (washub != conf.bot->hub)
  537. fatal(STR("MEMORY HACKED"), 0);
  538. check_mypid();
  539. } else if (conf.bot->hub || conf.bot->localhub)
  540. send_timesync(-1);
  541. check_bind_time(&nowtm);
  542. if (dcc_autoaway)
  543. check_autoaway();
  544. if (conf.bot->localhub)
  545. conf_add_userlist_bots();
  546. /* flushlogs(); */
  547. }
  548. static void core_halfhourly()
  549. {
  550. if (conf.bot->hub) {
  551. write_userfile(-1);
  552. if (link_cleartext)
  553. putlog(LOG_WARN, "*", STR("'link_cleartext' currently enabled. This is a security risk. Disable with '%sset link_cleartext 0'"), settings.dcc_prefix);
  554. } else
  555. check_maxfiles();
  556. }
  557. static void startup_checks(int hack) {
  558. /* for compatability with old conf files
  559. * only check/use conf file if it exists and settings.homedir is empty.
  560. * if settings.homedir is NOT empty, just erase the conf file if it exists
  561. * otherwise, assume we're working only with the struct */
  562. /* Only error out with missing homedir when we aren't editing the binary */
  563. if (settings.dynamic_initialized[0])
  564. bin_to_conf(do_confedit ? 0 : 1); /* read our memory from settings[] into conf[] */
  565. if (do_confedit)
  566. confedit(); /* this will exit() */
  567. if (!updating)
  568. parseconf(1);
  569. fixmod(binname);
  570. if (!can_stat(binname))
  571. werr(ERR_BINSTAT);
  572. fill_conf_bot();
  573. // if (((!conf.bot || !conf.bot->nick) || (!conf.bot->hub && conf.bot->localhub)) && !used_B) {
  574. if (!used_B) {
  575. if (do_killbot[0]) {
  576. const char *what = (kill_sig == SIGKILL ? "kill" : "restart");
  577. if (conf_killbot(conf.bots, do_killbot, NULL, kill_sig) == 0)
  578. printf(STR("'%s' successfully %sed.\n"), do_killbot, what);
  579. else {
  580. printf(STR("Error %sing '%s'\n"), what, do_killbot);
  581. if (kill_sig == SIGHUP)
  582. spawnbot(do_killbot);
  583. }
  584. exit(0);
  585. } else {
  586. /* this needs to be both hub/leaf */
  587. if (update_bin) { /* invokved with -u/-U */
  588. if (!conf.bot)
  589. updating = UPDATE_EXIT; //if we don't have a botlist, dont bother with restarting bots...
  590. // if (updating == UPDATE_AUTO && conf.bot && conf.bot->pid)
  591. // kill(conf.bot->pid, SIGHUP);
  592. updatebin(DP_STDOUT, update_bin, 1); /* will call restart all bots */
  593. /* never reached */
  594. exit(0);
  595. }
  596. if (!conf.bots || !conf.bots->nick) /* no bots ! */
  597. werr(ERR_NOBOTS);
  598. spawnbots(conf.bots);
  599. exit(0); /* our job is done! */
  600. }
  601. }
  602. if (!conf.bot)
  603. werr(ERR_NOBOT);
  604. if (conf.bot->disabled)
  605. werr(ERR_BOTDISABLED);
  606. if (!conf.bot->hub && !conf.bot->localhub)
  607. free_conf_bots(conf.bots); /* not a localhub, so no need to store all bot info */
  608. }
  609. static const char *fake_md5 = "596a96cc7bf9108cd896f33c44aedc8a";
  610. void console_init();
  611. void ctcp_init();
  612. void update_init();
  613. void server_init();
  614. void irc_init();
  615. void channels_init();
  616. void compress_init();
  617. void share_init();
  618. int main(int argc, char **argv)
  619. {
  620. #ifndef DEBUG
  621. check_trace(1);
  622. #endif
  623. if (init_openssl()) {
  624. fprintf(stderr, "Unable to initialize/find OpenSSL.\n");
  625. return 1;
  626. }
  627. /* Initialize variables and stuff */
  628. timer_update_now(&egg_timeval_now);
  629. now = egg_timeval_now.sec;
  630. mypid = getpid();
  631. myuid = geteuid();
  632. srandom(now % (mypid + getppid()) * randint(1000));
  633. setlimits();
  634. init_signals();
  635. if (strcmp(fake_md5, STR("596a96cc7bf9108cd896f33c44aedc8a"))) {
  636. unlink(argv[0]);
  637. fatal(STR("!! Invalid binary"), 0);
  638. }
  639. binname = getfullbinname(argv[0]);
  640. if (chdir(dirname(binname)))
  641. werr(ERR_BINSTAT);
  642. /* Find a temporary tempdir until we load binary data */
  643. /* setup initial tempdir as /tmp until we read in tmpdir from conf */
  644. if (Tempfile::FindDir() == ERROR)
  645. werr(ERR_TMPSTAT);
  646. /* This allows -2/-0 to be used without an initialized binary */
  647. // if (!(argc == 2 && (!strcmp(argv[1], "-2") || !strcmp(argv[1], "0")))) {
  648. // doesn't work correctly yet, if we don't go in here, our settings stay encrypted
  649. if (argc == 2 && !strcmp(argv[1], STR("-q"))) {
  650. if (settings_initialized()) exit(4); /* initialized */
  651. exit(5); /* not initialized */
  652. }
  653. if (argc == 2 && !strcmp(argv[1], STR("-p"))) {
  654. if (settings_initialized()) exit(4); /* initialized */
  655. exit(5); /* not initialized */
  656. }
  657. /* return the size of our settings struct */
  658. if (argc == 2 && !strcmp(argv[1], STR("-3"))) {
  659. printf("%d %zu\n", SETTINGS_VER, sizeof(settings_t));
  660. exit(0);
  661. }
  662. {
  663. bool read_stdin = 0;
  664. if (argc == 2 && !strcmp(argv[1], STR("-Q")))
  665. read_stdin =1;
  666. check_sum(binname, argc >= 3 && !strcmp(argv[1], STR("-q")) ? argv[2] : NULL, read_stdin);
  667. }
  668. #ifndef DEBUG
  669. if (myuid == 0 || getuid() == 0) {
  670. fprintf(stderr, "Don't run as root.\n");
  671. return 1;
  672. }
  673. #endif
  674. // Now settings struct is decrypted
  675. if (!checked_bin_buf)
  676. exit(1);
  677. #ifdef STOP_UAC
  678. {
  679. int nvpair[2] = { SSIN_UACPROC, UAC_NOPRINT };
  680. setsysinfo(SSI_NVPAIRS, (char *) nvpair, 1, NULL, 0);
  681. }
  682. #endif
  683. init_conf(); /* establishes conf and sets to defaults */
  684. /* Version info! */
  685. simple_snprintf(ver, sizeof(ver), STR("[%s] Wraith %s"), settings.packname, egg_version);
  686. simple_snprintf(version, sizeof(version), STR("%s%s (%li)"), ver,
  687. #ifdef DEBUG
  688. "(d)",
  689. #else
  690. "",
  691. #endif
  692. (long)buildts);
  693. memcpy(&nowtm, gmtime(&now), sizeof(struct tm));
  694. lastmin = nowtm.tm_min;
  695. if (argc)
  696. dtx_arg(argc, argv);
  697. for (size_t i = 0; i < PREFIXLEN - 1; ++i)
  698. if (settings.prefix[i] != SETTINGS_HEADER[0])
  699. werr(ERR_BADPASS);
  700. sdprintf(STR("my euid: %d my uuid: %d, my ppid: %d my pid: %d"), myuid, getuid(), (int)getppid(), (int)mypid);
  701. /* Check and load conf file */
  702. startup_checks(0);
  703. if (!socksfile && ((conf.bot->localhub && !updating) || !conf.bot->localhub)) {
  704. if ((conf.bot->pid > 0) && conf.bot->pid_file) {
  705. sdprintf(STR("%s is already running, pid: %d"), conf.bot->nick, (int)conf.bot->pid);
  706. exit(1);
  707. }
  708. }
  709. safe_to_log = 1;
  710. init_flags(); /* needed to establish FLAGS[] */
  711. core_binds_init();
  712. init_dcc(); /* needed if we are going to make any dcc */
  713. init_net(); /* needed for socklist[] */
  714. init_userent(); /* needed before loading userfile */
  715. init_party(); /* creates party[] */
  716. Auth::InitTimer();
  717. init_vars(); /* needed for cfg */
  718. init_botcmd();
  719. init_responses();
  720. egg_dns_init();
  721. channels_init();
  722. if (!conf.bot->hub) {
  723. server_init();
  724. ctcp_init();
  725. }
  726. share_init();
  727. update_init();
  728. console_init();
  729. chanprog();
  730. strlcpy(botuser, conf.username ? conf.username : origbotname, sizeof(botuser));
  731. if (!conf.bot->hub && conf.bot->localhub)
  732. sdprintf(STR("I am localhub (%s)"), conf.bot->nick);
  733. if (!sdebug && (conf.autocron && (conf.bot->hub || conf.bot->localhub)))
  734. check_crontab();
  735. /* Move into background? */
  736. use_stderr = 0; /* stop writing to stderr now! */
  737. if (backgrd) {
  738. if (!socksfile) {
  739. mypid = do_fork();
  740. conf_setmypid(mypid);
  741. printf(STR("%s[%s%s%s]%s -%s- initiated %s(%s%d%s)%s\n"),
  742. BOLD(-1), BOLD_END(-1), settings.packname, BOLD(-1), BOLD_END(-1), conf.bot->nick,
  743. BOLD(-1), BOLD_END(-1), (int)mypid, BOLD(-1), BOLD_END(-1));
  744. } else
  745. writepid(conf.bot->pid_file, mypid);
  746. close_tty();
  747. } else {
  748. if (!socksfile)
  749. printf(STR("%s[%s%s%s]%s -%s- initiated\n"), BOLD(-1), BOLD_END(-1), settings.packname, BOLD(-1), BOLD_END(-1), conf.bot->nick);
  750. writepid(conf.bot->pid_file, mypid);
  751. }
  752. /* Terminal emulating dcc chat */
  753. if (!backgrd && term_z) {
  754. int n = new_dcc(&DCC_CHAT, sizeof(struct chat_info));
  755. setup_HQ(n);
  756. setsock(STDOUT, 0); /* Entry in net table */
  757. dprintf(n, STR("\n### ENTERING DCC CHAT SIMULATION ###\n\n"));
  758. dcc_chatter(n);
  759. }
  760. online_since = now;
  761. autolink_cycle(); /* Hurry and connect to tandem bots */
  762. timer_create_secs(1, STR("core_secondly"), (Function) core_secondly);
  763. timer_create_secs(10, STR("check_expired_dcc"), (Function) check_expired_dcc);
  764. timer_create_secs(10, STR("core_10secondly"), (Function) core_10secondly);
  765. timer_create_secs(30, STR("expire_simuls"), (Function) expire_simuls);
  766. timer_create_secs(60, STR("core_minutely"), (Function) core_minutely);
  767. timer_create_secs(60, STR("check_botnet_pings"), (Function) check_botnet_pings);
  768. timer_create_secs(60, STR("check_expired_ignores"), (Function) check_expired_ignores);
  769. timer_create_secs(1800, STR("core_halfhourly"), (Function) core_halfhourly);
  770. if (socksfile)
  771. readsocks(socksfile);
  772. if (!conf.bot->hub) {
  773. // Restarting in new method - don't enable irc.mod until after receiving userfile.
  774. if (reset_chans != 2)
  775. irc_init();
  776. }
  777. debug0(STR("main: entering loop"));
  778. while (1) {
  779. /* Lets move some of this here, reducing the numer of actual
  780. * calls to periodic_timers
  781. */
  782. timer_update_now(&egg_timeval_now);
  783. now = egg_timeval_now.sec;
  784. random(); /* jumble things up o_O */
  785. timer_run();
  786. if (socket_run() == 1) {
  787. /* Idle calls */
  788. if (!conf.bot->hub && server_online) {
  789. flush_modes();
  790. }
  791. }
  792. if (unlikely(do_restart)) {
  793. if (do_restart == 1)
  794. restart(-1);
  795. else { //rehash()
  796. reload_bin_data();
  797. rehash_ip();
  798. }
  799. do_restart = 0;
  800. }
  801. }
  802. return 0; /* never reached but what the hell */
  803. }
  804. /* vim: set sts=2 sw=2 ts=8 et: */