main.c 26 KB

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