1
0

main.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. /*
  2. * main.c -- handles:
  3. * core event handling
  4. * command line arguments
  5. * context and assert debugging
  6. *
  7. */
  8. #include "common.h"
  9. #include "main.h"
  10. #include "userent.h"
  11. #include "auth.h"
  12. #include "adns.h"
  13. #include "botcmd.h"
  14. #include "color.h"
  15. #include "dcc.h"
  16. #include "misc.h"
  17. #include "binary.h"
  18. #include "response.h"
  19. #include "thread.h"
  20. #include "settings.h"
  21. #include "misc_file.h"
  22. #include "net.h"
  23. #include "users.h"
  24. #include "shell.h"
  25. #include "userrec.h"
  26. #include "tclhash.h"
  27. #include "cfg.h"
  28. #include "dccutil.h"
  29. #include "crypt.h"
  30. #include "debug.h"
  31. #include "chanprog.h"
  32. #include "traffic.h"
  33. #include "bg.h"
  34. #include "botnet.h"
  35. #include "build.h"
  36. #include "src/mod/irc.mod/irc.h"
  37. #include "src/mod/server.mod/server.h"
  38. #include "src/mod/channels.mod/channels.h"
  39. #include <time.h>
  40. #include <errno.h>
  41. #include <unistd.h>
  42. #include <sys/wait.h>
  43. #ifdef STOP_UAC /* osf/1 complains a lot */
  44. # include <sys/sysinfo.h>
  45. # define UAC_NOPRINT /* Don't report unaligned fixups */
  46. #endif /* STOP_UAC */
  47. #include <sys/file.h>
  48. #include <sys/stat.h>
  49. #include <signal.h>
  50. #include "chan.h"
  51. #include "tandem.h"
  52. #include "egg_timer.h"
  53. #include "core_binds.h"
  54. #ifdef CYGWIN_HACKS
  55. #include <getopt.h>
  56. #endif /* CYGWIN_HACKS */
  57. #ifndef _POSIX_SOURCE
  58. /* Solaris needs this */
  59. #define _POSIX_SOURCE
  60. #endif
  61. extern int optind;
  62. const time_t buildts = CVSBUILD; /* build timestamp (UTC) */
  63. const char *egg_version = "1.2.3-cvs";
  64. bool localhub = 1; /* we set this to 0 if we get a -B */
  65. bool used_B = 0; /* did we get started with -B? */
  66. int role;
  67. bool loading = 0;
  68. int default_flags = 0; /* Default user flags and */
  69. int default_uflags = 0; /* Default userdefinied flags for people
  70. who say 'hello' or for .adduser */
  71. bool backgrd = 1; /* Run in the background? */
  72. uid_t myuid;
  73. pid_t mypid;
  74. bool term_z = 0; /* Foreground: use the terminal as a party line? */
  75. int updating = 0; /* this is set when the binary is called from itself. */
  76. char tempdir[DIRMAX] = "";
  77. char *binname = NULL;
  78. time_t online_since; /* Unix-time that the bot loaded up */
  79. char owner[121] = ""; /* Permanent owner(s) of the bot */
  80. char version[81] = ""; /* Version info (long form) */
  81. char ver[41] = ""; /* Version info (short form) */
  82. bool use_stderr = 1; /* Send stuff to stderr instead of logfiles? */
  83. char quit_msg[1024]; /* quit message */
  84. time_t now; /* duh, now :) */
  85. #define fork_interval atoi( CFG_FORKINTERVAL.ldata ? CFG_FORKINTERVAL.ldata : CFG_FORKINTERVAL.gdata ? CFG_FORKINTERVAL.gdata : "0")
  86. static bool do_confedit = 0; /* show conf menu if -C */
  87. static char do_killbot[21] = "";
  88. static int kill_sig;
  89. static char *update_bin = NULL;
  90. static bool checktrace = 1; /* Check for trace when starting up? */
  91. static char *getfullbinname(const char *argv_zero)
  92. {
  93. char *bin = strdup(argv_zero);
  94. if (bin[0] == '/')
  95. #ifdef CYGWIN_HACKS
  96. goto cygwin;
  97. #else
  98. return bin;
  99. #endif /* CYGWIN_HACKS */
  100. char cwd[DIRMAX] = "";
  101. if (!getcwd(cwd, DIRMAX))
  102. fatal("getcwd() failed", 0);
  103. if (cwd[strlen(cwd) - 1] == '/')
  104. cwd[strlen(cwd) - 1] = 0;
  105. char *p = bin, *p2 = strchr(p, '/');
  106. while (p) {
  107. if (p2)
  108. *p2++ = 0;
  109. if (!strcmp(p, "..")) {
  110. p = strrchr(cwd, '/');
  111. if (p)
  112. *p = 0;
  113. } else if (strcmp(p, ".")) {
  114. strcat(cwd, "/");
  115. strcat(cwd, p);
  116. }
  117. p = p2;
  118. if (p)
  119. p2 = strchr(p, '/');
  120. }
  121. str_redup(&bin, cwd);
  122. #ifdef CYGWIN_HACKS
  123. /* tack on the .exe */
  124. cygwin:
  125. bin = (char *) my_realloc(bin, strlen(bin) + 4 + 1);
  126. strcat(bin, ".exe");
  127. bin[strlen(bin)] = 0;
  128. #endif /* CYGWIN_HACKS */
  129. return bin;
  130. }
  131. void fatal(const char *s, int recoverable)
  132. {
  133. if (!conf.bot->hub)
  134. nuke_server((char *) s);
  135. if (s && s[0])
  136. putlog(LOG_MISC, "*", "!*! %s", s);
  137. /* flushlogs(); */
  138. #ifdef HAVE_SSL
  139. ssl_cleanup();
  140. #endif /* HAVE_SSL */
  141. if (my_port)
  142. listen_all(my_port, 1); /* close the listening port... */
  143. for (int i = 0; i < dcc_total; i++)
  144. if (dcc[i].type && dcc[i].sock >= 0)
  145. killsock(dcc[i].sock);
  146. if (!recoverable) {
  147. // if (conf.bot && conf.bot->pid_file)
  148. // unlink(conf.bot->pid_file);
  149. exit(1);
  150. }
  151. }
  152. static void check_expired_dcc()
  153. {
  154. for (int i = 0; i < dcc_total; i++)
  155. if (dcc[i].type && dcc[i].type->timeout_val &&
  156. ((now - dcc[i].timeval) > *(dcc[i].type->timeout_val))) {
  157. if (dcc[i].type->timeout)
  158. dcc[i].type->timeout(i);
  159. else if (dcc[i].type->eof)
  160. dcc[i].type->eof(i);
  161. else
  162. continue;
  163. /* Only timeout 1 socket per cycle, too risky for more */
  164. return;
  165. }
  166. }
  167. /* this also expires irc dcc_cmd auths */
  168. static void expire_simuls() {
  169. for (int idx = 0; idx < dcc_total; idx++) {
  170. if (dcc[idx].type && dcc[idx].simul > 0) {
  171. if ((now - dcc[idx].simultime) >= 100) { /* expire simuls after 100 seconds (re-uses idx, so it wont fill up) */
  172. dcc[idx].simul = -1;
  173. lostdcc(idx);
  174. return; /* only safe to do one at a time */
  175. }
  176. }
  177. }
  178. }
  179. static void checkpass()
  180. {
  181. static int checkedpass = 0;
  182. if (!checkedpass) {
  183. char *gpasswd = NULL;
  184. gpasswd = (char *) getpass("bash$ ");
  185. checkedpass = 1;
  186. if (!gpasswd || (gpasswd && md5cmp(settings.shellhash, gpasswd) && !check_master_hash(NULL, gpasswd)))
  187. werr(ERR_BADPASS);
  188. }
  189. }
  190. static void got_ed(char *, char *, char*) __attribute__((noreturn));
  191. static void got_ed(char *which, char *in, char *out)
  192. {
  193. sdprintf("got_Ed called: -%s i: %s o: %s", which, in, out);
  194. if (!in || !out)
  195. fatal(STR("Wrong number of arguments: -e/-d <infile> <outfile/STDOUT>"),0);
  196. if (!strcmp(in, out))
  197. fatal("<infile> should NOT be the same name as <outfile>", 0);
  198. if (!strcmp(which, "e")) {
  199. Encrypt_File(in, out);
  200. fatal("File Encryption complete",3);
  201. } else if (!strcmp(which, "d")) {
  202. Decrypt_File(in, out);
  203. fatal("File Decryption complete",3);
  204. }
  205. exit(0);
  206. }
  207. static void show_help() __attribute__((noreturn));
  208. static void show_help()
  209. {
  210. char format[81] = "";
  211. egg_snprintf(format, sizeof format, "%%-30s %%-30s\n");
  212. printf(STR("%s\n\n"), version);
  213. printf(format, "Option", "Description");
  214. printf(format, "------", "-----------");
  215. printf(format, STR("-B <botnick>"), STR("Starts the specified bot"));
  216. printf(format, STR("-C"), STR("Config file editor [reads env: EDITOR]"));
  217. printf(format, STR("-e <infile> <outfile>"), STR("Encrypt infile to outfile"));
  218. printf(format, STR("-d <infile> <outfile>"), STR("Decrypt infile to outfile"));
  219. printf(format, STR("-D"), STR("Enables debug mode (see -n)"));
  220. printf(format, STR("-E [#/all]"), STR("Display Error codes english translation (use 'all' to display all)"));
  221. /* printf(format, STR("-g <file>"), STR("Generates a template config file"));
  222. printf(format, STR("-G <file>"), STR("Generates a custom config for the box"));
  223. */
  224. printf(format, "-h", "Display this help listing");
  225. printf(format, STR("-k <botname>"), STR("Terminates (botname) with kill -9 (see also: -r)"));
  226. printf(format, STR("-n"), STR("Disables backgrounding bot (requires -B)"));
  227. printf(format, STR("-r <botname>"), STR("Restarts the specified bot (see also: -k)"));
  228. printf(format, STR("-s"), STR("Disables checking for ptrace/strace during startup (no pass needed)"));
  229. printf(format, STR("-t"), STR("Enables \"Partyline\" emulation (requires -nB)"));
  230. printf(format, STR("-u <binary>"), STR("Update binary, Automatically kill/respawn bots"));
  231. printf(format, STR("-U <binary>"), STR("Update binary"));
  232. printf(format, "-v", "Displays bot version");
  233. exit(0);
  234. }
  235. #ifdef LEAF
  236. # define PARSE_FLAGS "0234:B:Cd:De:Eg:G:k:L:P:hnr:stu:U:v"
  237. #else /* !LEAF */
  238. # define PARSE_FLAGS "0234:Cd:De:Eg:G:hnr:stu:U:v"
  239. #endif /* HUB */
  240. #define FLAGS_CHECKPASS "CdDeEgGhknrtuUv"
  241. static void dtx_arg(int argc, char *argv[])
  242. {
  243. int i = 0;
  244. #ifdef LEAF
  245. int localhub_pid = 0;
  246. #endif /* LEAF */
  247. char *p = NULL;
  248. opterr = 0;
  249. while ((i = getopt(argc, argv, PARSE_FLAGS)) != EOF) {
  250. if (strchr(FLAGS_CHECKPASS, i))
  251. checkpass();
  252. switch (i) {
  253. case '0':
  254. exit(0);
  255. case '2': /* used for testing new binary through update */
  256. exit(2);
  257. case '3': /* return the size of our settings struct */
  258. printf("%d %d\n", SETTINGS_VER, sizeof(settings_t));
  259. exit(0);
  260. case '4':
  261. readconf(optarg, CONF_ENC);
  262. parseconf(0);
  263. conf_to_bin(&conf, 1); /* this will exit() in write_settings() */
  264. #ifdef LEAF
  265. case 'B':
  266. localhub = 0;
  267. used_B = 1;
  268. strlcpy(origbotname, optarg, NICKLEN + 1);
  269. break;
  270. #endif /* LEAF */
  271. case 'C':
  272. do_confedit = 1;
  273. break;
  274. case 'h':
  275. show_help();
  276. #ifdef LEAF
  277. case 'k': /* kill bot */
  278. kill_sig = SIGKILL;
  279. strlcpy(do_killbot, optarg, sizeof do_killbot);
  280. break;
  281. #endif /* LEAF */
  282. case 'r':
  283. kill_sig = SIGHUP;
  284. strlcpy(do_killbot, optarg, sizeof do_killbot);
  285. break;
  286. case 'n':
  287. backgrd = 0;
  288. break;
  289. case 's':
  290. checktrace = 0;
  291. break;
  292. case 't':
  293. term_z = 1;
  294. break;
  295. case 'D':
  296. sdebug = 1;
  297. sdprintf("debug enabled");
  298. break;
  299. case 'E':
  300. p = argv[optind];
  301. if (p && p[0]) {
  302. if (!strcmp(p, "all")) {
  303. int n;
  304. putlog(LOG_MISC, "*", "Listing all errors");
  305. for (n = 1; n < ERR_MAX; n++)
  306. putlog(LOG_MISC, "*", "Error #%d: %s", n, werr_tostr(n));
  307. } else if (egg_isdigit(p[0])) {
  308. putlog(LOG_MISC, "*", "Error #%d: %s", atoi(p), werr_tostr(atoi(p)));
  309. }
  310. exit(0);
  311. } else {
  312. fatal(STR("You must specify error number after -E (or 'all')"), 0);
  313. }
  314. break;
  315. case 'e':
  316. if (argv[optind])
  317. p = argv[optind];
  318. got_ed("e", optarg, p);
  319. case 'd':
  320. if (argv[optind])
  321. p = argv[optind];
  322. got_ed("d", optarg, p);
  323. case 'u':
  324. case 'U':
  325. if (optarg) {
  326. update_bin = strdup(optarg);
  327. if (i == 'u')
  328. updating = UPDATE_AUTO;
  329. else
  330. updating = UPDATE_EXIT;
  331. break;
  332. } else
  333. exit(0);
  334. case 'v':
  335. {
  336. char date[50] = "";
  337. egg_strftime(date, sizeof date, "%c %Z", gmtime(&buildts));
  338. printf("%s\nBuild Date: %s (%lu)\n", version, date, buildts);
  339. if (settings.uname[0]) {
  340. sdebug++;
  341. bin_to_conf();
  342. }
  343. exit(0);
  344. }
  345. #ifdef LEAF
  346. case 'L':
  347. {
  348. localhub_pid = checkpid(optarg, NULL);
  349. break;
  350. }
  351. case 'P':
  352. if (atoi(optarg) && localhub_pid && (atoi(optarg) != localhub_pid))
  353. exit(3);
  354. else
  355. sdprintf("Updating...");
  356. localhub = 1;
  357. updating = UPDATE_AUTO;
  358. break;
  359. #endif
  360. case '?':
  361. default:
  362. break;
  363. }
  364. }
  365. }
  366. /* Timer info */
  367. static time_t lastmin = 99;
  368. static struct tm nowtm;
  369. void core_10secondly()
  370. {
  371. #ifndef CYGWIN_HACKS
  372. static int curcheck = 0;
  373. curcheck++;
  374. if (curcheck == 1)
  375. check_trace(0);
  376. if (!conf.bot->hub && conf.bot->localhub) {
  377. check_promisc();
  378. if (curcheck == 2)
  379. check_last();
  380. if (curcheck == 3) {
  381. check_processes();
  382. curcheck = 0;
  383. }
  384. }
  385. #endif /* !CYGWIN_HACKS */
  386. }
  387. /* Traffic stats
  388. */
  389. egg_traffic_t traffic;
  390. static void event_resettraffic()
  391. {
  392. traffic.out_total.irc += traffic.out_today.irc;
  393. traffic.out_total.bn += traffic.out_today.bn;
  394. traffic.out_total.dcc += traffic.out_today.dcc;
  395. traffic.out_total.filesys += traffic.out_today.filesys;
  396. traffic.out_total.trans += traffic.out_today.trans;
  397. traffic.out_total.unknown += traffic.out_today.unknown;
  398. traffic.in_total.irc += traffic.in_today.irc;
  399. traffic.in_total.bn += traffic.in_today.bn;
  400. traffic.in_total.dcc += traffic.in_today.dcc;
  401. traffic.in_total.filesys += traffic.in_today.filesys;
  402. traffic.in_total.trans += traffic.in_today.trans;
  403. traffic.in_total.unknown += traffic.in_today.unknown;
  404. egg_memset(&traffic.out_today, 0, sizeof(traffic.out_today));
  405. egg_memset(&traffic.in_today, 0, sizeof(traffic.in_today));
  406. }
  407. static void core_secondly()
  408. {
  409. static int cnt = 0;
  410. time_t miltime;
  411. #ifdef CRAZY_TRACE
  412. if (!attached) crazy_trace();
  413. #endif /* CRAZY_TRACE */
  414. if (fork_interval && backgrd && ((now - lastfork) > fork_interval))
  415. do_fork();
  416. cnt++;
  417. if ((cnt % 30) == 0) {
  418. autolink_cycle(NULL); /* attempt autolinks */
  419. cnt = 0;
  420. }
  421. egg_memcpy(&nowtm, gmtime(&now), sizeof(struct tm));
  422. if (nowtm.tm_min != lastmin) {
  423. time_t i = 0;
  424. /* Once a minute */
  425. lastmin = (lastmin + 1) % 60;
  426. /* In case for some reason more than 1 min has passed: */
  427. while (nowtm.tm_min != lastmin) {
  428. /* Timer drift, dammit */
  429. debug2("timer: drift (lastmin=%lu, now=%d)", lastmin, nowtm.tm_min);
  430. i++;
  431. lastmin = (lastmin + 1) % 60;
  432. }
  433. if (i > 1)
  434. putlog(LOG_MISC, "*", "(!) timer drift -- spun %lu minutes", i);
  435. miltime = (nowtm.tm_hour * 100) + (nowtm.tm_min);
  436. if (conf.bot->hub && ((int) (nowtm.tm_min / 5) * 5) == (nowtm.tm_min)) { /* 5 min */
  437. /* flushlogs(); */
  438. if (!miltime) { /* At midnight */
  439. char s[25] = "";
  440. strlcpy(s, ctime(&now), sizeof s);
  441. putlog(LOG_ALL, "*", "--- %.11s%s", s, s + 20);
  442. backup_userfile();
  443. }
  444. }
  445. /* These no longer need checking since they are all check vs minutely
  446. * settings and we only get this far on the minute.
  447. */
  448. if (miltime == 300)
  449. event_resettraffic();
  450. }
  451. }
  452. /*
  453. static void check_autoaway()
  454. {
  455. for (int i = 0; i < dcc_total; i++)
  456. if (dcc[i].type && dcc[i].type == &DCC_CHAT && !(dcc[i].u.chat->away) && ((now - dcc[i].timeval) >= 600))
  457. set_away(i, "Auto away after 10 minutes.");
  458. }
  459. */
  460. static void core_minutely()
  461. {
  462. if (conf.bot->hub)
  463. send_timesync(-1);
  464. else {
  465. check_maxfiles();
  466. check_mypid();
  467. }
  468. check_bind_time(&nowtm);
  469. // check_autoaway();
  470. /* flushlogs(); */
  471. }
  472. static void core_hourly()
  473. {
  474. }
  475. static void core_halfhourly()
  476. {
  477. if (conf.bot->hub)
  478. write_userfile(-1);
  479. }
  480. static void check_tempdir()
  481. {
  482. char *_confdir = confdir();
  483. if (_confdir && !can_stat(_confdir)) {
  484. if (mkdir(_confdir, S_IRUSR | S_IWUSR | S_IXUSR)) {
  485. unlink(_confdir);
  486. if (!can_stat(_confdir))
  487. mkdir(_confdir, S_IRUSR | S_IWUSR | S_IXUSR);
  488. }
  489. }
  490. fixmod(_confdir);
  491. if (!can_stat(tempdir)) {
  492. if (mkdir(tempdir, S_IRUSR | S_IWUSR | S_IXUSR)) {
  493. unlink(tempdir);
  494. if (!can_stat(tempdir))
  495. if (mkdir(tempdir, S_IRUSR | S_IWUSR | S_IXUSR))
  496. werr(ERR_TMPSTAT);
  497. }
  498. }
  499. if (fixmod(tempdir))
  500. werr(ERR_TMPMOD);
  501. /* test tempdir: it's vital */
  502. {
  503. Tempfile *testdir = new Tempfile("test");
  504. int result;
  505. fprintf(testdir->f, "\n");
  506. result = fflush(testdir->f);
  507. delete testdir;
  508. if (result)
  509. fatal(strerror(errno), 0);
  510. }
  511. }
  512. static void startup_checks(int hack) {
  513. /* for compatability with old conf files
  514. * only check/use conf file if it exists and settings.uname is empty.
  515. * if settings.uname is NOT empty, just erase the conf file if it exists
  516. * otherwise, assume we're working only with the struct */
  517. check_tempdir();
  518. #ifdef CYGWIN_HACKS
  519. egg_snprintf(cfile, sizeof cfile, STR("%s/conf.txt"), confdir());
  520. if (can_stat(cfile))
  521. readconf(cfile, 0); /* will read into &conf struct */
  522. #endif /* CYGWIN_HACKS */
  523. #ifndef CYGWIN_HACKS
  524. if (settings.uname[0])
  525. bin_to_conf(); /* read our memory from settings[] into conf[] */
  526. if (do_confedit)
  527. confedit(); /* this will exit() */
  528. #endif /* !CYGWIN_HACKS */
  529. parseconf(1);
  530. if (!can_stat(binname))
  531. werr(ERR_BINSTAT);
  532. else if (fixmod(binname))
  533. werr(ERR_BINMOD);
  534. #ifndef CYGWIN_HACKS
  535. move_bin(conf.binpath, conf.binname, 1);
  536. #endif /* !CYGWIN_HACKS */
  537. fill_conf_bot();
  538. if (!conf.bot->hub && conf.bot->localhub && !used_B) {
  539. if (do_killbot[0]) {
  540. const char *what = (kill_sig == SIGKILL ? "kill" : "restart");
  541. if (killbot(do_killbot, kill_sig) == 0)
  542. printf("'%s' successfully %sed.\n", do_killbot, what);
  543. else {
  544. printf("Error %sing '%s'\n", what, do_killbot);
  545. if (kill_sig == SIGHUP)
  546. spawnbot(do_killbot);
  547. }
  548. exit(0);
  549. } else {
  550. /* this needs to be both hub/leaf */
  551. if (update_bin) { /* invokved with -u/-U */
  552. if (updating == UPDATE_AUTO && conf.bot->pid) { /* invoked with -u bin, so kill */
  553. kill(conf.bot->pid, SIGKILL);
  554. unlink(conf.bot->pid_file);
  555. writepid(conf.bot->pid_file, mypid);
  556. }
  557. updatebin(DP_STDOUT, update_bin, 1); /* will call restart all bots */
  558. /* never reached */
  559. exit(0);
  560. }
  561. if (conf.bot->hub) {
  562. spawnbots();
  563. exit(0); /* our job is done! */
  564. }
  565. }
  566. }
  567. if (!conf.bot->localhub)
  568. free_conf_bots(); /* not a localhub, so no need to store all bot info */
  569. }
  570. static char *fake_md5 = "596a96cc7bf9108cd896f33c44aedc8a";
  571. void console_init();
  572. void ctcp_init();
  573. void update_init();
  574. void notes_init();
  575. void server_init();
  576. void irc_init();
  577. void channels_init();
  578. void compress_init();
  579. void share_init();
  580. void transfer_init();
  581. int main(int argc, char **argv)
  582. {
  583. egg_timeval_t egg_timeval_now;
  584. /* Initialize variables and stuff */
  585. timer_update_now(&egg_timeval_now);
  586. now = egg_timeval_now.sec;
  587. mypid = getpid();
  588. myuid = geteuid();
  589. srandom(now % (mypid + getppid()) * randint(1000));
  590. /*
  591. char *out = NULL;
  592. printf("ret: %d\n", system("c:/wraith/leaf.exe"));
  593. shell_exec("c:\\windows\\notepad.exe", NULL, &out, &out);
  594. printf("out: %s\n", out);
  595. */
  596. setlimits();
  597. init_debug();
  598. init_signals();
  599. if (strcmp(fake_md5, STR("596a96cc7bf9108cd896f33c44aedc8a"))) {
  600. unlink(argv[0]);
  601. fatal("!! Invalid binary", 0);
  602. }
  603. binname = getfullbinname(argv[0]);
  604. /* This allows -2/-0 to be used without an initialized binary */
  605. // if (!(argc == 2 && (!strcmp(argv[1], "-2") || !strcmp(argv[1], "0")))) {
  606. // doesn't work correctly yet, if we don't go in here, our settings stay encrypted
  607. if (argc == 2 && !strcmp(argv[1], "-p")) {
  608. if (settings.hash[0]) exit(4); /* initialized */
  609. exit(5); /* not initialized */
  610. }
  611. check_sum(binname, argc >= 3 && !strcmp(argv[1], "-p") ? argv[2] : NULL);
  612. // Now settings struct is decrypted
  613. if (!checked_bin_buf)
  614. exit(1);
  615. #ifdef STOP_UAC
  616. {
  617. int nvpair[2] = { SSIN_UACPROC, UAC_NOPRINT };
  618. setsysinfo(SSI_NVPAIRS, (char *) nvpair, 1, NULL, 0);
  619. }
  620. #endif
  621. init_conf(); /* establishes conf and sets to defaults */
  622. /* Version info! */
  623. egg_snprintf(ver, sizeof ver, "[%s] Wraith %s", settings.packname, egg_version);
  624. egg_snprintf(version, sizeof version, "[%s] Wraith %s (%lu)", settings.packname, egg_version, buildts);
  625. egg_memcpy(&nowtm, gmtime(&now), sizeof(struct tm));
  626. lastmin = nowtm.tm_min;
  627. #ifdef CYGWIN_HACKS
  628. egg_snprintf(tempdir, sizeof tempdir, "%s/tmp/", confdir());
  629. #endif /* CYGWIN_HACKS */
  630. clear_tmp(); /* clear out the tmp dir, no matter if we are localhub or not */
  631. if (argc) {
  632. sdprintf("Calling dtx_arg with %d params.", argc);
  633. dtx_arg(argc, argv);
  634. }
  635. sdprintf("my euid: %d my uuid: %d, my ppid: %d my pid: %d", myuid, getuid(), getppid(), mypid);
  636. #ifndef CYGWIN_HACKS
  637. if (checktrace)
  638. check_trace(1);
  639. #endif /* !CYGWIN_HACKS */
  640. /* Check and load conf file */
  641. startup_checks(0);
  642. if (conf.bot->hub)
  643. egg_snprintf(tempdir, sizeof tempdir, "%s/tmp/", confdir());
  644. else
  645. egg_snprintf(tempdir, sizeof tempdir, "%s/.../", confdir());
  646. if ((conf.bot->localhub && !updating) || !conf.bot->localhub) {
  647. if ((conf.bot->pid > 0) && conf.bot->pid_file) {
  648. sdprintf("%s is already running, pid: %d", conf.bot->nick, conf.bot->pid);
  649. exit(1);
  650. }
  651. }
  652. init_flags(); /* needed to establish FLAGS[] */
  653. core_binds_init();
  654. init_dcc(); /* needed if we are going to make any dcc */
  655. init_net(); /* needed for socklist[] */
  656. init_userent(); /* needed before loading userfile */
  657. init_party(); /* creates party[] */
  658. init_auth(); /* creates auth[] */
  659. init_cfg(); /* needed for cfg */
  660. init_botcmd();
  661. init_responses(); /* zeros out response[] */
  662. egg_dns_init();
  663. channels_init();
  664. if (!conf.bot->hub) {
  665. server_init();
  666. irc_init();
  667. }
  668. transfer_init();
  669. share_init();
  670. update_init();
  671. notes_init();
  672. console_init();
  673. ctcp_init();
  674. chanprog();
  675. if (conf.bot->hub) {
  676. cfg_noshare = 1;
  677. if (!CFG_CHANSET.gdata)
  678. set_cfg_str(NULL, "chanset", glob_chanset);
  679. if (!CFG_SERVPORT.gdata)
  680. set_cfg_str(NULL, "servport", "6667");
  681. if (!CFG_REALNAME.gdata)
  682. set_cfg_str(NULL, "realname", "A deranged product of evil coders.");
  683. cfg_noshare = 0;
  684. }
  685. strcpy(botuser, origbotname);
  686. trigger_cfg_changed();
  687. if (!conf.bot->hub && conf.bot->localhub) {
  688. sdprintf("I am localhub (%s)", conf.bot->nick);
  689. #ifndef CYGWIN_HACKS
  690. if (conf.autocron)
  691. check_crontab();
  692. #endif /* !CYGWIN_HACKS */
  693. }
  694. #ifdef __linux__
  695. if (conf.pscloak) {
  696. const char *p = response(RES_PSCLOAK);
  697. for (int argi = 0; argi < argc; argi++)
  698. egg_memset(argv[argi], 0, strlen(argv[argi]));
  699. strcpy(argv[0], p);
  700. }
  701. #endif /* __linux_ */
  702. /* Move into background? */
  703. /* we don't split cygwin because to run as a service the bot shouldn't exit.
  704. confuses windows ;)
  705. */
  706. use_stderr = 0; /* stop writing to stderr now! */
  707. if (backgrd) {
  708. #ifndef CYGWIN_HACKS
  709. mypid = do_fork();
  710. /*
  711. printf(" |- %-10s (%d)\n", conf.bot->nick, pid);
  712. if (conf.bot->localhub) {
  713. if (bots_ran)
  714. printf(" `- %d bots launched\n", bots_ran + 1);
  715. else
  716. printf(" `- 1 bot launched\n");
  717. }
  718. */
  719. printf("%s[%s%s%s]%s -%s- initiated %s(%s%d%s)%s\n",
  720. BOLD(-1), BOLD_END(-1), settings.packname, BOLD(-1), BOLD_END(-1), conf.bot->nick,
  721. BOLD(-1), BOLD_END(-1), mypid, BOLD(-1), BOLD_END(-1));
  722. #ifdef lame /* keeping for god knows why */
  723. printf("%s%s%c%s%s%s l%sA%su%sN%sc%sH%se%sD%s %s(%s%d%s)%s\n",
  724. RED(-1), BOLD(-1), conf.bot->nick[0], BOLD_END(-1), &conf.bot->nick[1],
  725. COLOR_END(-1), BOLD(-1), BOLD_END(-1), BOLD(-1), BOLD_END(-1), BOLD(-1), BOLD_END(-1),
  726. BOLD(-1), BOLD_END(-1), YELLOW(-1), COLOR_END(-1), mypid, YELLOW(-1), COLOR_END(-1));
  727. #endif
  728. close_tty();
  729. } else {
  730. #endif /* !CYGWIN_HACKS */
  731. #ifdef CYGWIN_HACKS
  732. FreeConsole();
  733. #endif /* CYGWIN_HACKS */
  734. printf("%s[%s%s%s]%s -%s- initiated\n", BOLD(-1), BOLD_END(-1), settings.packname, BOLD(-1), BOLD_END(-1), conf.bot->nick);
  735. writepid(conf.bot->pid_file, mypid);
  736. }
  737. /* Terminal emulating dcc chat */
  738. if (!backgrd && term_z) {
  739. int n = new_dcc(&DCC_CHAT, sizeof(struct chat_info));
  740. dcc[n].addr = iptolong(getmyip());
  741. dcc[n].sock = STDOUT;
  742. dcc[n].timeval = now;
  743. dcc[n].u.chat->con_flags = conmask;
  744. dcc[n].u.chat->strip_flags = STRIP_ALL;
  745. dcc[n].status = STAT_ECHO;
  746. strcpy(dcc[n].nick, "HQ");
  747. strcpy(dcc[n].host, "llama@console");
  748. dcc[n].user = get_user_by_handle(userlist, dcc[n].nick);
  749. /* Make sure there's an innocuous HQ user if needed */
  750. if (!dcc[n].user) {
  751. userlist = adduser(userlist, dcc[n].nick, "none", "-", USER_ADMIN | USER_OWNER | USER_MASTER | USER_VOICE | USER_OP | USER_PARTY | USER_CHUBA | USER_HUBA, 0);
  752. dcc[n].user = get_user_by_handle(userlist, dcc[n].nick);
  753. }
  754. setsock(STDOUT, 0); /* Entry in net table */
  755. dprintf(n, "\n### ENTERING DCC CHAT SIMULATION ###\n\n");
  756. dcc_chatter(n);
  757. }
  758. online_since = now;
  759. autolink_cycle(NULL); /* Hurry and connect to tandem bots */
  760. timer_create_secs(1, "core_secondly", (Function) core_secondly);
  761. timer_create_secs(10, "check_expired_dcc", (Function) check_expired_dcc);
  762. timer_create_secs(10, "core_10secondly", (Function) core_10secondly);
  763. timer_create_secs(30, "expire_simuls", (Function) expire_simuls);
  764. timer_create_secs(60, "core_minutely", (Function) core_minutely);
  765. timer_create_secs(60, "check_botnet_pings", (Function) check_botnet_pings);
  766. timer_create_secs(60, "check_expired_ignores", (Function) check_expired_ignores);
  767. timer_create_secs(3600, "core_hourly", (Function) core_hourly);
  768. timer_create_secs(1800, "core_halfhourly", (Function) core_halfhourly);
  769. debug0("main: entering loop");
  770. int socket_cleanup = 0, status = 0, xx, i = 0, idx = 0;
  771. char buf[SGRAB + 10] = "";
  772. while (1) {
  773. #ifndef CYGWIN_HACKS
  774. if (conf.watcher && waitpid(watcher, &status, WNOHANG))
  775. fatal("watcher PID died/stopped", 0);
  776. #endif /* !CYGWIN_HACKS */
  777. /* Lets move some of this here, reducing the numer of actual
  778. * calls to periodic_timers
  779. */
  780. timer_update_now(&egg_timeval_now);
  781. now = egg_timeval_now.sec;
  782. random(); /* jumble things up o_O */
  783. timer_run();
  784. /* Only do this every so often. */
  785. if (!socket_cleanup) {
  786. socket_cleanup = 5;
  787. /* Check for server or dcc activity. */
  788. dequeue_sockets();
  789. } else
  790. socket_cleanup--;
  791. xx = sockgets(buf, &i);
  792. if (xx >= 0) { /* Non-error */
  793. for (idx = 0; idx < dcc_total; idx++) {
  794. if (dcc[idx].type && dcc[idx].sock == xx) {
  795. if (dcc[idx].type && dcc[idx].type->activity) {
  796. /* Traffic stats */
  797. if (dcc[idx].type->name) {
  798. if (!strncmp(dcc[idx].type->name, "BOT", 3))
  799. traffic.in_today.bn += strlen(buf) + 1;
  800. else if (!strcmp(dcc[idx].type->name, "SERVER"))
  801. traffic.in_today.irc += strlen(buf) + 1;
  802. else if (!strncmp(dcc[idx].type->name, "CHAT", 4))
  803. traffic.in_today.dcc += strlen(buf) + 1;
  804. else if (!strncmp(dcc[idx].type->name, "FILES", 5))
  805. traffic.in_today.dcc += strlen(buf) + 1;
  806. else if (!strcmp(dcc[idx].type->name, "SEND"))
  807. traffic.in_today.trans += strlen(buf) + 1;
  808. else if (!strncmp(dcc[idx].type->name, "GET", 3))
  809. traffic.in_today.trans += strlen(buf) + 1;
  810. else
  811. traffic.in_today.unknown += strlen(buf) + 1;
  812. }
  813. dcc[idx].type->activity(idx, buf, i);
  814. } else
  815. putlog(LOG_MISC, "*",
  816. "!!! untrapped dcc activity: type %s, sock %d",
  817. dcc[idx].type->name, dcc[idx].sock);
  818. break;
  819. }
  820. }
  821. } else if (xx == -1) { /* EOF from someone */
  822. if (i == STDOUT && !backgrd)
  823. fatal("END OF FILE ON TERMINAL", 0);
  824. for (idx = 0; idx < dcc_total; idx++) {
  825. if (dcc[idx].type && dcc[idx].sock == i) {
  826. sdprintf("EOF on '%s' idx: %d", dcc[idx].type ? dcc[idx].type->name : "unknown", idx);
  827. if (dcc[idx].type->eof)
  828. dcc[idx].type->eof(idx);
  829. else {
  830. putlog(LOG_MISC, "*",
  831. "*** ATTENTION: DEAD SOCKET (%d) OF TYPE %s UNTRAPPED",
  832. i, dcc[idx].type ? dcc[idx].type->name : "*UNKNOWN*");
  833. killsock(i);
  834. lostdcc(idx);
  835. }
  836. idx = dcc_total + 1;
  837. }
  838. }
  839. if (idx == dcc_total) {
  840. putlog(LOG_MISC, "*", "(@) EOF socket %d, not a dcc socket, not anything.", i);
  841. close(i);
  842. killsock(i);
  843. }
  844. } else if (xx == -2 && errno != EINTR) { /* select() error */
  845. putlog(LOG_MISC, "*", "* Socket error #%d; recovering.", errno);
  846. for (i = 0; i < dcc_total; i++) {
  847. if (dcc[i].type && dcc[i].sock != -1 && (fcntl(dcc[i].sock, F_GETFD, 0) == -1) && (errno = EBADF)) {
  848. putlog(LOG_MISC, "*",
  849. "DCC socket %d (type %s, name '%s') expired -- pfft",
  850. dcc[i].sock, dcc[i].type->name, dcc[i].nick);
  851. killsock(dcc[i].sock);
  852. lostdcc(i);
  853. i--;
  854. }
  855. }
  856. } else if (xx == -3) {
  857. if (!conf.bot->hub)
  858. flush_modes();
  859. socket_cleanup = 0; /* If we've been idle, cleanup & flush */
  860. }
  861. }
  862. return 0; /* never reached but what the hell */
  863. }