main.c 29 KB

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