main.c 29 KB

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