1
0

main.c 30 KB

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