main.c 26 KB

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