main.c 27 KB

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