main.c 28 KB

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