main.c 29 KB

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