main.c 27 KB

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