main.c 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  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. #ifdef CYGWIN_HACKS
  123. goto cygwin;
  124. #else
  125. return bin;
  126. #endif /* CYGWIN_HACKS */
  127. if (!getcwd(cwd, PATH_MAX))
  128. fatal(STR("getcwd() failed"), 0);
  129. if (cwd[0] && cwd[strlen(cwd) - 1] == '/')
  130. cwd[strlen(cwd) - 1] = 0;
  131. p = bin;
  132. p2 = strchr(p, '/');
  133. while (p) {
  134. if (p2)
  135. *p2++ = 0;
  136. if (!strcmp(p, "..")) {
  137. p = strrchr(cwd, '/');
  138. if (p)
  139. *p = 0;
  140. } else if (strcmp(p, ".")) {
  141. strlcat(cwd, "/", sizeof(cwd));
  142. strlcat(cwd, p, sizeof(cwd));
  143. }
  144. p = p2;
  145. if (p)
  146. p2 = strchr(p, '/');
  147. }
  148. str_redup(&bin, cwd);
  149. #ifdef CYGWIN_HACKS
  150. /* tack on the .exe */
  151. cygwin:
  152. bin = (char *) my_realloc(bin, strlen(bin) + 4 + 1);
  153. strcat(bin, ".exe");
  154. bin[strlen(bin)] = 0;
  155. #endif /* CYGWIN_HACKS */
  156. /* Fix for symlinked binaries */
  157. if (!realpath(bin, buf))
  158. fatal(STR("realpath() failed"), 0);
  159. size_t len = strlen(buf);
  160. bin = (char *) my_realloc(bin, len + 1);
  161. strlcpy(bin, buf, len + 1);
  162. return bin;
  163. }
  164. void fatal(const char *s, int recoverable)
  165. {
  166. sdprintf(STR("FATAL(%d) %s"), recoverable, s);
  167. if (server_online)
  168. nuke_server((char *) s);
  169. if (s && s[0])
  170. putlog(LOG_MISC, "*", STR("!*! %s"), s);
  171. /* flushlogs(); */
  172. if (my_port)
  173. listen_all(my_port, 1); /* close the listening port... */
  174. sdprintf(STR("Closing %d sockets"), dcc_total);
  175. for (int i = 0; i < dcc_total; i++) {
  176. if (dcc[i].type && dcc[i].sock >= 0) {
  177. sdprintf(STR("Closing %s dcc(%d)"), dcc[i].type->name, i);
  178. killsock(dcc[i].sock);
  179. lostdcc(i);
  180. }
  181. }
  182. if (!recoverable) {
  183. // if (conf.bot && conf.bot->pid_file)
  184. // unlink(conf.bot->pid_file);
  185. exit(1);
  186. }
  187. }
  188. static void check_expired_dcc()
  189. {
  190. for (int i = 0; i < dcc_total; i++)
  191. if (dcc[i].type && dcc[i].type->timeout_val &&
  192. ((now - dcc[i].timeval) > *(dcc[i].type->timeout_val))) {
  193. if (dcc[i].type->timeout)
  194. dcc[i].type->timeout(i);
  195. else if (dcc[i].type->eof)
  196. dcc[i].type->eof(i);
  197. else
  198. continue;
  199. /* Only timeout 1 socket per cycle, too risky for more */
  200. return;
  201. }
  202. }
  203. /* this also expires irc dcc_cmd auths */
  204. static void expire_simuls() {
  205. for (int idx = 0; idx < dcc_total; idx++) {
  206. if (dcc[idx].type && dcc[idx].simul >= 0) {
  207. if ((now - dcc[idx].simultime) >= 100) { /* expire simuls after 100 seconds (re-uses idx, so it wont fill up) */
  208. dcc[idx].simul = -1;
  209. lostdcc(idx);
  210. }
  211. }
  212. }
  213. }
  214. static int checkedpass = 0;
  215. static void checkpass()
  216. {
  217. int (*hash_cmp) (const char *, const char *) = NULL;
  218. size_t hashlen = strlen(settings.shellhash);
  219. if (hashlen == 32)
  220. hash_cmp = md5cmp;
  221. else if (hashlen == 40)
  222. hash_cmp = sha1cmp;
  223. else if (hashlen == 47)
  224. hash_cmp = salted_sha1cmp;
  225. #define SHELL_PROMPT STR("Enter your binary password: ")
  226. #ifdef HAVE_GETPASSPHRASE
  227. /* Solaris' getpass() truncates at 8 */
  228. char *gpasswd = (char*) getpassphrase(SHELL_PROMPT);
  229. #else
  230. char *gpasswd = (char*) getpass(SHELL_PROMPT);
  231. #endif
  232. if (!gpasswd)
  233. werr(ERR_BADPASS);
  234. checkedpass = hash_cmp(settings.shellhash, gpasswd);
  235. /* Most PASS_MAX are 256.. but it's not clear */
  236. OPENSSL_cleanse(gpasswd, 30);
  237. if (checkedpass)
  238. werr(ERR_BADPASS);
  239. }
  240. static void got_ed(char *, char *, char*) __attribute__((noreturn));
  241. static void got_ed(char *which, char *in, char *out)
  242. {
  243. sdprintf(STR("got_Ed called: -%s i: %s o: %s"), which, in, out);
  244. if (!in || !out)
  245. fatal(STR("Wrong number of arguments: -e/-d <infile> <outfile/STDOUT>"),0);
  246. if (!strcmp(in, out))
  247. fatal(STR("<infile> should NOT be the same name as <outfile>"), 0);
  248. if (!strcmp(which, "e")) {
  249. Encrypt_File(in, out);
  250. fatal(STR("File Encryption complete"),3);
  251. } else if (!strcmp(which, "d")) {
  252. Decrypt_File(in, out);
  253. fatal(STR("File Decryption complete"),3);
  254. }
  255. exit(0);
  256. }
  257. static void show_help() __attribute__((noreturn));
  258. static void show_help()
  259. {
  260. const char format[] = "%-30s %-30s\n";
  261. printf(STR("%s\n\n"), version);
  262. printf(STR("%s [options] [botnick[.conf]]\n"));
  263. printf(STR("Not supplying any options will make all bots in the binary spawn.\n"));
  264. printf(format, STR("Option"), STR("Description"));
  265. printf(format, STR("------"), STR("-----------"));
  266. printf(format, STR("[-B] <botnick>"), STR("Starts the specified bot [deprecated]"));
  267. printf(format, STR("-c"), STR("Config file editor [reads env: EDITOR] [No auto update]"));
  268. printf(format, STR("-C"), STR("Config file editor [reads env: EDITOR]"));
  269. // printf(format, STR("-e <infile> <outfile>"), STR("Encrypt infile to outfile"));
  270. // printf(format, STR("-d <infile> <outfile>"), STR("Decrypt infile to outfile"));
  271. printf(format, STR("-D"), STR("Enables debug mode (see -n)"));
  272. printf(format, STR("-E [error code]"), STR("Display Error codes english translation"));
  273. /* printf(format, STR("-g <file>"), STR("Generates a template config file"));
  274. printf(format, STR("-G <file>"), STR("Generates a custom config for the box"));
  275. */
  276. printf(format, STR("-h"), STR("Display this help listing"));
  277. printf(format, STR("-k <botname>"), STR("Terminates (botname) with kill -9 (see also: -r)"));
  278. printf(format, STR("-n"), STR("Disables backgrounding bot (requires [-B] <botnick>)"));
  279. printf(format, STR("-q <pack.cfg>"), STR("Initialize the binary with the given pack.cfg (Can only be done once per binary)"));
  280. printf(format, STR("-Q"), STR("Securely initialize the binary by reading the PackConfig from stdin (paste). (Can only be done once per binary)"));
  281. printf(format, STR("-r <botname>"), STR("Restarts the specified bot (see also: -k)"));
  282. // printf(format, STR("-s"), STR("Disables checking for ptrace/strace during startup (no pass needed)"));
  283. printf(format, STR("-t"), STR("Enables \"Partyline\" emulation (requires -nB)"));
  284. printf(format, STR("-u <binary>"), STR("Update binary, Automatically kill/respawn bots"));
  285. printf(format, STR("-U <binary>"), STR("Update binary"));
  286. printf(format, STR("-v"), STR("Displays bot version"));
  287. exit(0);
  288. }
  289. // leaf: BkLP
  290. #define PARSE_FLAGS STR("0234:aB:cCd:De:EH:k:hnr:tu:U:v")
  291. #define FLAGS_CHECKPASS STR("cCdDeEhknrtuUv")
  292. static void dtx_arg(int& argc, char *argv[])
  293. {
  294. int i = 0, checked_pass = 0;
  295. char *p = NULL;
  296. #ifdef DEBUG
  297. checked_pass = 1;
  298. #endif
  299. opterr = 0;
  300. while ((i = getopt(argc, argv, PARSE_FLAGS)) != EOF) {
  301. if (strchr(FLAGS_CHECKPASS, i) && !checked_pass) {
  302. checkpass();
  303. checked_pass++;
  304. }
  305. switch (i) {
  306. case '0':
  307. exit(0);
  308. case '2': /* used for testing new binary through update */
  309. exit(2);
  310. case '4':
  311. readconf(optarg, CONF_ENC);
  312. expand_tilde(&conf.binpath);
  313. expand_tilde(&conf.datadir);
  314. parseconf(0);
  315. conf_to_bin(&conf, 0, 6); /* this will exit() in write_settings() */
  316. case 'a':
  317. unlink(binname);
  318. exit(0);
  319. case 'B':
  320. used_B = 1;
  321. strlcpy(origbotname, optarg, HANDLEN + 1);
  322. strlcpy(origbotnick, optarg, HANDLEN + 1);
  323. break;
  324. case 'H':
  325. printf("SHA1 (%s): %s\n", optarg, SHA1(optarg));
  326. printf("MD5 (%s): %s\n", optarg, MD5(optarg));
  327. // do_crypt_console();
  328. exit(0);
  329. break;
  330. case 'c':
  331. do_confedit = 2;
  332. break;
  333. case 'C':
  334. do_confedit = 1;
  335. break;
  336. case 'h':
  337. show_help();
  338. case 'k': /* kill bot */
  339. kill_sig = SIGKILL;
  340. strlcpy(do_killbot, optarg, sizeof do_killbot);
  341. break;
  342. case 'r':
  343. kill_sig = SIGHUP;
  344. strlcpy(do_killbot, optarg, sizeof do_killbot);
  345. break;
  346. case 'n':
  347. backgrd = 0;
  348. break;
  349. case 't':
  350. term_z = 1;
  351. break;
  352. case 'D':
  353. sdebug = 1;
  354. sdprintf("debug enabled");
  355. break;
  356. case 'E':
  357. p = argv[optind];
  358. if (p && p[0] && egg_isdigit(p[0])) {
  359. putlog(LOG_MISC, "*", STR("Error #%d: %s"), atoi(p), werr_tostr(atoi(p)));
  360. } else {
  361. int n;
  362. putlog(LOG_MISC, "*", STR("Listing all errors"));
  363. for (n = 1; n < ERR_MAX; n++)
  364. putlog(LOG_MISC, "*", STR("Error #%d: %s"), n, werr_tostr(n));
  365. }
  366. exit(0);
  367. break;
  368. case 'e':
  369. if (argv[optind])
  370. p = argv[optind];
  371. got_ed("e", optarg, p);
  372. case 'd':
  373. if (argv[optind])
  374. p = argv[optind];
  375. got_ed("d", optarg, p);
  376. case 'u':
  377. case 'U':
  378. if (optarg) {
  379. update_bin = strdup(optarg);
  380. if (i == 'u')
  381. updating = UPDATE_AUTO;
  382. else
  383. updating = UPDATE_EXIT;
  384. break;
  385. } else
  386. exit(0);
  387. case 'v':
  388. {
  389. char date[50] = "";
  390. strftime(date, sizeof date, "%c %Z", gmtime(&buildts));
  391. printf(STR("%s\nBuild Date: %s (%s%lu%s)\n"), version, date, BOLD(-1), buildts, BOLD_END(-1));
  392. 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));
  393. printf(STR("pack: %d conf: %d settings_t: %d prefix: %d pad: %d\n"), SIZE_PACK, SIZE_CONF, sizeof(settings_t), PREFIXLEN, SIZE_PAD);
  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. }
  547. static void startup_checks(int hack) {
  548. /* for compatability with old conf files
  549. * only check/use conf file if it exists and settings.uname is empty.
  550. * if settings.uname is NOT empty, just erase the conf file if it exists
  551. * otherwise, assume we're working only with the struct */
  552. #ifdef CYGWIN_HACKS
  553. simple_snprintf(cfile, sizeof cfile, STR("./conf.txt"));
  554. if (can_stat(cfile))
  555. readconf(cfile, 0); /* will read into &conf struct */
  556. conf_checkpids(conf.bots);
  557. #endif /* CYGWIN_HACKS */
  558. #ifndef CYGWIN_HACKS
  559. /* Only error out with missing homedir when we aren't editing the binary */
  560. if (settings.uname[0])
  561. bin_to_conf(do_confedit ? 0 : 1); /* read our memory from settings[] into conf[] */
  562. if (do_confedit)
  563. confedit(); /* this will exit() */
  564. #endif /* !CYGWIN_HACKS */
  565. if (!updating)
  566. parseconf(1);
  567. fixmod(binname);
  568. if (!can_stat(binname))
  569. werr(ERR_BINSTAT);
  570. #ifndef CYGWIN_HACKS
  571. move_bin(conf.binpath, conf.binname, 1);
  572. #endif /* !CYGWIN_HACKS */
  573. fill_conf_bot();
  574. // if (((!conf.bot || !conf.bot->nick) || (!conf.bot->hub && conf.bot->localhub)) && !used_B) {
  575. if (!used_B) {
  576. if (do_killbot[0]) {
  577. const char *what = (kill_sig == SIGKILL ? "kill" : "restart");
  578. if (conf_killbot(conf.bots, do_killbot, NULL, kill_sig) == 0)
  579. printf(STR("'%s' successfully %sed.\n"), do_killbot, what);
  580. else {
  581. printf(STR("Error %sing '%s'\n"), what, do_killbot);
  582. if (kill_sig == SIGHUP)
  583. spawnbot(do_killbot);
  584. }
  585. exit(0);
  586. } else {
  587. /* this needs to be both hub/leaf */
  588. if (update_bin) { /* invokved with -u/-U */
  589. if (!conf.bot)
  590. updating = UPDATE_EXIT; //if we don't have a botlist, dont bother with restarting bots...
  591. // if (updating == UPDATE_AUTO && conf.bot && conf.bot->pid)
  592. // kill(conf.bot->pid, SIGHUP);
  593. updatebin(DP_STDOUT, update_bin, 1); /* will call restart all bots */
  594. /* never reached */
  595. exit(0);
  596. }
  597. if (!conf.bots || !conf.bots->nick) /* no bots ! */
  598. werr(ERR_NOBOTS);
  599. spawnbots(conf.bots);
  600. exit(0); /* our job is done! */
  601. }
  602. }
  603. if (!conf.bot)
  604. werr(ERR_NOBOT);
  605. if (conf.bot->disabled)
  606. werr(ERR_BOTDISABLED);
  607. if (!conf.bot->hub && !conf.bot->localhub)
  608. free_conf_bots(conf.bots); /* not a localhub, so no need to store all bot info */
  609. }
  610. static char *fake_md5 = "596a96cc7bf9108cd896f33c44aedc8a";
  611. void console_init();
  612. void ctcp_init();
  613. void update_init();
  614. void server_init();
  615. void irc_init();
  616. void channels_init();
  617. void compress_init();
  618. void share_init();
  619. void transfer_init();
  620. void profile(int, char **);
  621. int main(int argc, char **argv)
  622. {
  623. egg_timeval_t egg_timeval_now;
  624. #ifndef DEBUG
  625. #ifndef CYGWIN_HACKS
  626. check_trace(1);
  627. #endif /* !CYGWIN_HACKS */
  628. #endif
  629. /* Initialize variables and stuff */
  630. timer_update_now(&egg_timeval_now);
  631. now = egg_timeval_now.sec;
  632. mypid = getpid();
  633. myuid = geteuid();
  634. srandom(now % (mypid + getppid()) * randint(1000));
  635. /*
  636. char *out = NULL;
  637. printf("ret: %d\n", system("c:/wraith/leaf.exe"));
  638. shell_exec("c:\\windows\\notepad.exe", NULL, &out, &out);
  639. printf("out: %s\n", out);
  640. */
  641. setlimits();
  642. init_debug();
  643. init_signals();
  644. #ifdef DEBUG
  645. if (argc >= 2 && !strcmp(argv[1], "--"))
  646. profile(argc, argv);
  647. #endif /* DEBUG */
  648. if (strcmp(fake_md5, STR("596a96cc7bf9108cd896f33c44aedc8a"))) {
  649. unlink(argv[0]);
  650. fatal(STR("!! Invalid binary"), 0);
  651. }
  652. binname = getfullbinname(argv[0]);
  653. if (chdir(dirname(binname)))
  654. werr(ERR_BINSTAT);
  655. /* Find a temporary tempdir until we load binary data */
  656. /* setup initial tempdir as /tmp until we read in tmpdir from conf */
  657. if (Tempfile::FindDir() == ERROR)
  658. werr(ERR_TMPSTAT);
  659. /* This allows -2/-0 to be used without an initialized binary */
  660. // if (!(argc == 2 && (!strcmp(argv[1], "-2") || !strcmp(argv[1], "0")))) {
  661. // doesn't work correctly yet, if we don't go in here, our settings stay encrypted
  662. if (argc == 2 && !strcmp(argv[1], STR("-q"))) {
  663. if (settings.hash[0]) exit(4); /* initialized */
  664. exit(5); /* not initialized */
  665. }
  666. if (argc == 2 && !strcmp(argv[1], STR("-p"))) {
  667. if (settings.hash[0]) exit(4); /* initialized */
  668. exit(5); /* not initialized */
  669. }
  670. /* return the size of our settings struct */
  671. if (argc == 2 && !strcmp(argv[1], STR("-3"))) {
  672. printf("%d %zu\n", SETTINGS_VER, sizeof(settings_t));
  673. exit(0);
  674. }
  675. {
  676. bool read_stdin = 0;
  677. if (argc == 2 && !strcmp(argv[1], STR("-Q")))
  678. read_stdin =1;
  679. check_sum(binname, argc >= 3 && !strcmp(argv[1], STR("-q")) ? argv[2] : NULL, read_stdin);
  680. }
  681. // Now settings struct is decrypted
  682. if (!checked_bin_buf)
  683. exit(1);
  684. #ifdef STOP_UAC
  685. {
  686. int nvpair[2] = { SSIN_UACPROC, UAC_NOPRINT };
  687. setsysinfo(SSI_NVPAIRS, (char *) nvpair, 1, NULL, 0);
  688. }
  689. #endif
  690. init_conf(); /* establishes conf and sets to defaults */
  691. /* Version info! */
  692. simple_snprintf(ver, sizeof(ver), STR("[%s] Wraith %s"), settings.packname, egg_version);
  693. simple_snprintf(version, sizeof(version), STR("%s (%lu)"), ver, buildts);
  694. memcpy(&nowtm, gmtime(&now), sizeof(struct tm));
  695. lastmin = nowtm.tm_min;
  696. if (argc)
  697. dtx_arg(argc, argv);
  698. sdprintf(STR("my euid: %d my uuid: %d, my ppid: %d my pid: %d"), myuid, getuid(), getppid(), mypid);
  699. /* Check and load conf file */
  700. startup_checks(0);
  701. if (!socksfile && ((conf.bot->localhub && !updating) || !conf.bot->localhub)) {
  702. if ((conf.bot->pid > 0) && conf.bot->pid_file) {
  703. sdprintf(STR("%s is already running, pid: %d"), conf.bot->nick, conf.bot->pid);
  704. exit(1);
  705. }
  706. }
  707. init_flags(); /* needed to establish FLAGS[] */
  708. core_binds_init();
  709. init_dcc(); /* needed if we are going to make any dcc */
  710. init_net(); /* needed for socklist[] */
  711. init_userent(); /* needed before loading userfile */
  712. init_party(); /* creates party[] */
  713. Auth::InitTimer();
  714. init_vars(); /* needed for cfg */
  715. init_botcmd();
  716. init_responses(); /* zeros out response[] */
  717. egg_dns_init();
  718. channels_init();
  719. if (!conf.bot->hub) {
  720. server_init();
  721. irc_init();
  722. ctcp_init();
  723. }
  724. transfer_init();
  725. share_init();
  726. update_init();
  727. console_init();
  728. chanprog();
  729. strlcpy(botuser, conf.username ? conf.username : origbotname, sizeof(botuser));
  730. if (!conf.bot->hub && conf.bot->localhub)
  731. sdprintf(STR("I am localhub (%s)"), conf.bot->nick);
  732. #ifndef CYGWIN_HACKS
  733. if (conf.autocron && (conf.bot->hub || conf.bot->localhub))
  734. check_crontab();
  735. #endif /* !CYGWIN_HACKS */
  736. /* Move into background? */
  737. /* we don't split cygwin because to run as a service the bot shouldn't exit.
  738. confuses windows ;)
  739. */
  740. use_stderr = 0; /* stop writing to stderr now! */
  741. if (backgrd) {
  742. #ifndef CYGWIN_HACKS
  743. if (!socksfile) {
  744. mypid = do_fork();
  745. conf_setmypid(mypid);
  746. printf(STR("%s[%s%s%s]%s -%s- initiated %s(%s%d%s)%s\n"),
  747. BOLD(-1), BOLD_END(-1), settings.packname, BOLD(-1), BOLD_END(-1), conf.bot->nick,
  748. BOLD(-1), BOLD_END(-1), mypid, BOLD(-1), BOLD_END(-1));
  749. } else
  750. writepid(conf.bot->pid_file, mypid);
  751. close_tty();
  752. } else {
  753. #endif /* !CYGWIN_HACKS */
  754. #ifdef CYGWIN_HACKS
  755. FreeConsole();
  756. #endif /* CYGWIN_HACKS */
  757. if (!socksfile)
  758. 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);
  759. writepid(conf.bot->pid_file, mypid);
  760. }
  761. /* Terminal emulating dcc chat */
  762. if (!backgrd && term_z) {
  763. int n = new_dcc(&DCC_CHAT, sizeof(struct chat_info));
  764. setup_HQ(n);
  765. setsock(STDOUT, 0); /* Entry in net table */
  766. dprintf(n, STR("\n### ENTERING DCC CHAT SIMULATION ###\n\n"));
  767. dcc_chatter(n);
  768. }
  769. online_since = now;
  770. autolink_cycle(NULL); /* Hurry and connect to tandem bots */
  771. timer_create_secs(1, STR("core_secondly"), (Function) core_secondly);
  772. timer_create_secs(10, STR("check_expired_dcc"), (Function) check_expired_dcc);
  773. timer_create_secs(10, STR("core_10secondly"), (Function) core_10secondly);
  774. timer_create_secs(30, STR("expire_simuls"), (Function) expire_simuls);
  775. timer_create_secs(60, STR("core_minutely"), (Function) core_minutely);
  776. timer_create_secs(60, STR("check_botnet_pings"), (Function) check_botnet_pings);
  777. timer_create_secs(60, STR("check_expired_ignores"), (Function) check_expired_ignores);
  778. timer_create_secs(3600, STR("core_hourly"), (Function) core_hourly);
  779. timer_create_secs(1800, STR("core_halfhourly"), (Function) core_halfhourly);
  780. if (socksfile)
  781. readsocks(socksfile);
  782. debug0(STR("main: entering loop"));
  783. int socket_cleanup = 0, xx, i = 0, idx = 0;
  784. char buf[SGRAB + 10] = "";
  785. while (1) {
  786. /* Lets move some of this here, reducing the numer of actual
  787. * calls to periodic_timers
  788. */
  789. timer_update_now(&egg_timeval_now);
  790. now = egg_timeval_now.sec;
  791. random(); /* jumble things up o_O */
  792. timer_run();
  793. /* Only do this every so often. */
  794. if (!socket_cleanup) {
  795. socket_cleanup = 5;
  796. /* Check for server or dcc activity. */
  797. dequeue_sockets();
  798. } else
  799. socket_cleanup--;
  800. xx = sockgets(buf, &i);
  801. if (xx >= 0) { /* Non-error */
  802. for (idx = 0; idx < dcc_total; idx++) {
  803. if (dcc[idx].type && dcc[idx].sock == xx) {
  804. if (dcc[idx].type && dcc[idx].type->activity) {
  805. /* Traffic stats */
  806. if (dcc[idx].type->name) {
  807. if (!strncmp(dcc[idx].type->name, "BOT", 3))
  808. traffic.in_today.bn += strlen(buf) + 1;
  809. else if (!strcmp(dcc[idx].type->name, "SERVER"))
  810. traffic.in_today.irc += strlen(buf) + 1;
  811. else if (!strncmp(dcc[idx].type->name, "CHAT", 4))
  812. traffic.in_today.dcc += strlen(buf) + 1;
  813. else if (!strncmp(dcc[idx].type->name, "FILES", 5))
  814. traffic.in_today.dcc += strlen(buf) + 1;
  815. else if (!strcmp(dcc[idx].type->name, "SEND"))
  816. traffic.in_today.trans += strlen(buf) + 1;
  817. else if (!strncmp(dcc[idx].type->name, "GET", 3))
  818. traffic.in_today.trans += strlen(buf) + 1;
  819. else
  820. traffic.in_today.unknown += strlen(buf) + 1;
  821. }
  822. dcc[idx].type->activity(idx, buf, (size_t) i);
  823. } else
  824. putlog(LOG_MISC, "*",
  825. STR("!!! untrapped dcc activity: type %s, sock %d"),
  826. dcc[idx].type->name, dcc[idx].sock);
  827. break;
  828. }
  829. }
  830. } else if (xx == -1) { /* EOF from someone */
  831. if (i == STDOUT && !backgrd)
  832. fatal(STR("END OF FILE ON TERMINAL"), 0);
  833. for (idx = 0; idx < dcc_total; idx++) {
  834. if (dcc[idx].type && dcc[idx].sock == i) {
  835. sdprintf(STR("EOF on '%s' idx: %d"), dcc[idx].type ? dcc[idx].type->name : "unknown", idx);
  836. if (dcc[idx].type->eof)
  837. dcc[idx].type->eof(idx);
  838. else {
  839. putlog(LOG_MISC, "*",
  840. STR("*** ATTENTION: DEAD SOCKET (%d) OF TYPE %s UNTRAPPED"),
  841. i, dcc[idx].type ? dcc[idx].type->name : "*UNKNOWN*");
  842. killsock(i);
  843. lostdcc(idx);
  844. }
  845. idx = dcc_total + 1;
  846. }
  847. }
  848. if (idx == dcc_total) {
  849. putlog(LOG_MISC, "*", STR("(@) EOF socket %d, not a dcc socket, not anything."), i);
  850. close(i);
  851. killsock(i);
  852. }
  853. } else if (xx == -2 && errno != EINTR) { /* select() error */
  854. putlog(LOG_MISC, "*", STR("* Socket error #%d; recovering."), errno);
  855. for (i = 0; i < dcc_total; i++) {
  856. if (dcc[i].type && dcc[i].sock != -1 && (fcntl(dcc[i].sock, F_GETFD, 0) == -1) && (errno = EBADF)) {
  857. putlog(LOG_MISC, "*",
  858. STR("DCC socket %d (type %s, name '%s') expired -- pfft"),
  859. dcc[i].sock, dcc[i].type->name, dcc[i].nick);
  860. killsock(dcc[i].sock);
  861. lostdcc(i);
  862. i--;
  863. }
  864. }
  865. } else if (xx == -3) {
  866. if (!conf.bot->hub)
  867. flush_modes();
  868. socket_cleanup = 0; /* If we've been idle, cleanup & flush */
  869. }
  870. if (do_restart) {
  871. if (do_restart == 1)
  872. restart(-1);
  873. else { //rehash()
  874. reload_bin_data();
  875. rehash_ip();
  876. }
  877. do_restart = 0;
  878. }
  879. }
  880. return 0; /* never reached but what the hell */
  881. }