main.c 28 KB

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