shell.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  1. /* I hereby release this into the Public Domain - Bryan Drewery */
  2. /*
  3. * shell.c -- handles:
  4. *
  5. * All shell related functions
  6. * -shell_exec()
  7. * -botconfig parsing
  8. * -check_*()
  9. * -crontab functions
  10. *
  11. */
  12. #include "common.h"
  13. #include "shell.h"
  14. #include "chanprog.h"
  15. #include "set.h"
  16. #include "settings.h"
  17. #include "userrec.h"
  18. #include "net.h"
  19. #include "flags.h"
  20. #include "tandem.h"
  21. #include "main.h"
  22. #include "dccutil.h"
  23. #include "misc.h"
  24. #include "misc_file.h"
  25. #include "bg.h"
  26. #include "stat.h"
  27. #include "users.h"
  28. #include "botnet.h"
  29. #include "src/mod/server.mod/server.h"
  30. #include <sys/types.h>
  31. #include <pwd.h>
  32. #include <signal.h>
  33. #ifdef HAVE_SYS_PTRACE_H
  34. # include <sys/ptrace.h>
  35. #endif /* HAVE_SYS_PTRACE_H */
  36. #include <sys/wait.h>
  37. #include <sys/utsname.h>
  38. #include <pwd.h>
  39. #include <errno.h>
  40. #include <net/if.h>
  41. #include <sys/ioctl.h>
  42. #include <sys/socket.h>
  43. #include <ctype.h>
  44. #include <fcntl.h>
  45. #include <sys/stat.h>
  46. #include <unistd.h>
  47. #include <dirent.h>
  48. bool clear_tmpdir = 0;
  49. int my_system(const char *run)
  50. {
  51. #ifdef WIN32NOFUCK
  52. int ret = -1;
  53. PROCESS_INFORMATION pinfo;
  54. STARTUPINFO sinfo;
  55. memset(&sinfo, 0, sizeof(STARTUPINFO));
  56. sinfo.cb = sizeof(sinfo);
  57. sinfo.wShowWindow = SW_HIDE;
  58. sinfo.dwFlags |= STARTF_USESTDHANDLES;
  59. sinfo.hStdInput =
  60. sinfo.hStdOutput =
  61. sinfo.hStdError =
  62. ret =
  63. CreateProcess(NULL, (char *) run, NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS | DETACHED_PROCESS, NULL, NULL,
  64. (STARTUPINFO *) &sinfo, (PROCESS_INFORMATION *) &pinfo);
  65. if (ret == 0)
  66. return -1;
  67. else
  68. return 0;
  69. #else
  70. return system(run);
  71. #endif /* WIN32 */
  72. }
  73. void clear_tmp()
  74. {
  75. if (!clear_tmpdir)
  76. return;
  77. DIR *tmp = NULL;
  78. if (!(tmp = opendir(tempdir)))
  79. return;
  80. struct dirent *dir_ent = NULL;
  81. char *file = NULL;
  82. size_t flen = 0;
  83. while ((dir_ent = readdir(tmp))) {
  84. if (strncmp(dir_ent->d_name, ".pid.", 4) &&
  85. strncmp(dir_ent->d_name, ".u", 2) &&
  86. strcmp(dir_ent->d_name, ".bin.old") &&
  87. strncmp(dir_ent->d_name, STR(".socks-"), 7) &&
  88. strcmp(dir_ent->d_name, ".") &&
  89. strcmp(dir_ent->d_name, ".un") &&
  90. strcmp(dir_ent->d_name, "..")) {
  91. flen = strlen(dir_ent->d_name) + strlen(tempdir) + 1;
  92. file = (char *) my_calloc(1, flen);
  93. strlcat(file, tempdir, flen);
  94. strlcat(file, dir_ent->d_name, flen);
  95. file[strlen(file)] = 0;
  96. sdprintf("clear_tmp: %s", file);
  97. unlink(file);
  98. free(file);
  99. }
  100. }
  101. closedir(tmp);
  102. return;
  103. }
  104. void check_maxfiles()
  105. {
  106. int sock = -1, sock1 = -1 , bogus = 0, failed_close = 0;
  107. #ifdef USE_IPV6
  108. sock1 = getsock(0, AF_INET); /* fill up any lower avail */
  109. sock = getsock(0, AF_INET);
  110. #else
  111. sock1 = getsock(0);
  112. sock = getsock(0);
  113. #endif
  114. if (sock1 != -1)
  115. killsock(sock1);
  116. if (sock == -1) {
  117. return;
  118. } else
  119. killsock(sock);
  120. bogus = sock - socks_total - 4; //4 for stdin/stdout/stderr/dns
  121. if (bogus >= 50) { /* Attempt to close them */
  122. sdprintf("SOCK: %d BOGUS: %d SOCKS_TOTAL: %d", sock, bogus, socks_total);
  123. for (int i = 10; i < sock; i++) /* dont close lower sockets, they're probably legit */
  124. if (!findanysnum(i)) {
  125. if ((close(i)) == -1) /* try to close the BOGUS fd (likely a KQUEUE) */
  126. failed_close++;
  127. else
  128. bogus--;
  129. }
  130. if (bogus >= 150 || failed_close >= 50) {
  131. if (tands > 0) {
  132. botnet_send_chat(-1, conf.bot->nick, "Max FD reached, restarting...");
  133. botnet_send_bye("Max FD reached, restarting...");
  134. }
  135. nuke_server("brb");
  136. cycle_time = 0;
  137. restart(-1);
  138. } else if (bogus >= 100 && (bogus % 10) == 0) {
  139. putlog(LOG_WARN, "*", "* WARNING: $b%d$b bogus file descriptors detected, auto restart at 150", bogus);
  140. }
  141. }
  142. }
  143. void check_mypid()
  144. {
  145. pid_t pid = 0;
  146. if (can_stat(conf.bot->pid_file))
  147. pid = checkpid(conf.bot->nick, NULL);
  148. if (pid && (pid != getpid()))
  149. fatal(STR("getpid() does not match pid in file. Possible cloned process, exiting.."), 0);
  150. }
  151. #ifndef CYGWIN_HACKS
  152. char last_buf[128] = "";
  153. void check_last() {
  154. if (login == DET_IGNORE)
  155. return;
  156. if (conf.username) {
  157. char *out = NULL, buf[50] = "";
  158. simple_snprintf(buf, sizeof(buf), STR("last -10 %s"), conf.username);
  159. if (shell_exec(buf, NULL, &out, NULL)) {
  160. if (out) {
  161. char *p = NULL;
  162. p = strchr(out, '\n');
  163. if (p)
  164. *p = 0;
  165. if (strlen(out) > 10) {
  166. if (last_buf[0]) {
  167. if (strncmp(last_buf, out, sizeof(last_buf))) {
  168. char *work = NULL;
  169. size_t siz = strlen(out) + 7 + 2 + 1;
  170. work = (char *) my_calloc(1, siz);
  171. simple_snprintf(work, siz, STR("Login: %s"), out);
  172. detected(DETECT_LOGIN, work);
  173. free(work);
  174. }
  175. }
  176. strlcpy(last_buf, out, sizeof(last_buf));
  177. }
  178. free(out);
  179. }
  180. }
  181. }
  182. }
  183. void check_promisc()
  184. {
  185. #ifdef SIOCGIFCONF
  186. if (promisc == DET_IGNORE)
  187. return;
  188. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  189. if (sock < 0)
  190. return;
  191. struct ifconf ifcnf;
  192. char buf[1024] = "";
  193. ifcnf.ifc_len = sizeof(buf);
  194. ifcnf.ifc_buf = buf;
  195. if (ioctl(sock, SIOCGIFCONF, &ifcnf) < 0) {
  196. close(sock);
  197. return;
  198. }
  199. char *reqp = NULL, *end_req = NULL;
  200. reqp = buf; /* pointer to start of array */
  201. end_req = buf + ifcnf.ifc_len; /* pointer to end of array */
  202. while (reqp < end_req) {
  203. struct ifreq ifreq, *ifr = NULL;
  204. ifr = (struct ifreq *) reqp; /* start examining interface */
  205. ifreq = *ifr;
  206. if (!ioctl(sock, SIOCGIFFLAGS, &ifreq)) { /* we can read this interface! */
  207. /* sdprintf("Examing interface: %s", ifr->ifr_name); */
  208. if (ifreq.ifr_flags & IFF_PROMISC) {
  209. char which[101] = "";
  210. simple_snprintf(which, sizeof(which), STR("Detected promiscuous mode on interface: %s"), ifr->ifr_name);
  211. ioctl(sock, SIOCSIFFLAGS, &ifreq); /* set flags */
  212. detected(DETECT_PROMISC, which);
  213. break;
  214. }
  215. }
  216. /* move pointer to next array element (next interface) */
  217. reqp += sizeof(ifr->ifr_name) + sizeof(ifr->ifr_addr);
  218. }
  219. close(sock);
  220. #endif /* SIOCGIFCONF */
  221. }
  222. bool traced = 0;
  223. static void got_sigtrap(int z)
  224. {
  225. traced = 0;
  226. }
  227. void check_trace(int start)
  228. {
  229. if (trace == DET_IGNORE || trace == DET_WARN)
  230. trace = DET_DIE;
  231. // return;
  232. #ifdef DEBUG
  233. trace = DET_IGNORE;
  234. #endif /* DEBUG */
  235. if (trace == DET_IGNORE)
  236. return;
  237. pid_t parent = getpid();
  238. /* we send ourselves a SIGTRAP, if we recieve, we're not being traced, otherwise we are. */
  239. signal(SIGTRAP, got_sigtrap);
  240. traced = 1;
  241. raise(SIGTRAP);
  242. /* no longer need this__asm__("INT3"); //SIGTRAP */
  243. signal(SIGTRAP, SIG_DFL);
  244. if (!traced) {
  245. signal(SIGINT, got_sigtrap);
  246. traced = 1;
  247. raise(SIGINT);
  248. signal(SIGINT, SIG_DFL);
  249. }
  250. if (traced) {
  251. if (start) {
  252. kill(parent, SIGKILL);
  253. exit(1);
  254. } else
  255. detected(DETECT_TRACE, STR("I'm being traced!"));
  256. } else {
  257. if (!start)
  258. return;
  259. #ifndef __sun__
  260. int x, i;
  261. /* now, let's attempt to ptrace ourself */
  262. switch ((x = fork())) {
  263. case -1:
  264. return;
  265. case 0: //child
  266. i = ptrace(PT_ATTACH, parent, 0, 0);
  267. /* EPERM is given on fbsd when security.bsd.unprivileged_proc_debug=0 */
  268. if (i == -1 && errno != EPERM) {
  269. if (start) {
  270. kill(parent, SIGKILL);
  271. exit(1);
  272. } else
  273. detected(DETECT_TRACE, STR("I'm being traced!"));
  274. } else {
  275. waitpid(parent, NULL, 0);
  276. ptrace(PT_DETACH, parent, (char *) 1, 0);
  277. kill(parent, SIGCHLD);
  278. }
  279. exit(0);
  280. default: //parent
  281. waitpid(x, NULL, 0);
  282. }
  283. #endif
  284. }
  285. }
  286. #endif /* !CYGWIN_HACKS */
  287. int shell_exec(char *cmdline, char *input, char **output, char **erroutput)
  288. {
  289. if (!cmdline)
  290. return 0;
  291. Tempfile *in = NULL, *out = NULL, *err = NULL;
  292. int x;
  293. int parent = getpid();
  294. /* Set up temp files */
  295. in = new Tempfile("in");
  296. if (!in || in->error) {
  297. // putlog(LOG_ERRORS, "*" , "exec: Couldn't open '%s': %s", in->file, strerror(errno));
  298. if (in)
  299. delete in;
  300. return 0;
  301. }
  302. if (input) {
  303. if (fwrite(input, strlen(input), 1, in->f) != 1) {
  304. // putlog(LOG_ERRORS, "*", "exec: Couldn't write to '%s': %s", in->file, strerror(errno));
  305. delete in;
  306. return 0;
  307. }
  308. fseek(in->f, 0, SEEK_SET);
  309. }
  310. err = new Tempfile("err");
  311. if (!err || err->error) {
  312. // putlog(LOG_ERRORS, "*", "exec: Couldn't open '%s': %s", err->file, strerror(errno));
  313. delete in;
  314. if (err)
  315. delete err;
  316. return 0;
  317. }
  318. out = new Tempfile("out");
  319. if (!out || out->error) {
  320. // putlog(LOG_ERRORS, "*", "exec: Couldn't open '%s': %s", out->file, strerror(errno));
  321. delete in;
  322. delete err;
  323. if (out)
  324. delete out;
  325. return 0;
  326. }
  327. x = fork();
  328. if (x == -1) {
  329. putlog(LOG_ERRORS, "*", "exec: fork() failed: %s", strerror(errno));
  330. delete in;
  331. delete err;
  332. delete out;
  333. return 0;
  334. }
  335. if (x) { /* Parent: wait for the child to complete */
  336. int st = 0;
  337. size_t fs = 0;
  338. waitpid(x, &st, 0);
  339. /* child is now complete, read the files into buffers */
  340. delete in;
  341. fflush(out->f);
  342. fflush(err->f);
  343. if (erroutput) {
  344. char *buf = NULL;
  345. fseek(err->f, 0, SEEK_END);
  346. fs = ftell(err->f);
  347. if (fs == 0) {
  348. (*erroutput) = NULL;
  349. } else {
  350. buf = (char *) my_calloc(1, fs + 1);
  351. fseek(err->f, 0, SEEK_SET);
  352. fread(buf, 1, fs, err->f);
  353. buf[fs] = 0;
  354. (*erroutput) = buf;
  355. }
  356. }
  357. delete err;
  358. if (output) {
  359. char *buf = NULL;
  360. fseek(out->f, 0, SEEK_END);
  361. fs = ftell(out->f);
  362. if (fs == 0) {
  363. (*output) = NULL;
  364. } else {
  365. buf = (char *) my_calloc(1, fs + 1);
  366. fseek(out->f, 0, SEEK_SET);
  367. fread(buf, 1, fs, out->f);
  368. buf[fs] = 0;
  369. (*output) = buf;
  370. }
  371. }
  372. delete out;
  373. return 1;
  374. } else {
  375. /* Child: make fd's and set them up as std* */
  376. // int ind, outd, errd;
  377. char *argv[4] = { NULL, NULL, NULL, NULL };
  378. // ind = fileno(inpFile);
  379. // outd = fileno(outFile);
  380. // errd = fileno(errFile);
  381. if (dup2(in->fd, STDIN_FILENO) == (-1)) {
  382. kill(parent, SIGCHLD);
  383. exit(1);
  384. }
  385. if (dup2(out->fd, STDOUT_FILENO) == (-1)) {
  386. kill(parent, SIGCHLD);
  387. exit(1);
  388. }
  389. if (dup2(err->fd, STDERR_FILENO) == (-1)) {
  390. kill(parent, SIGCHLD);
  391. exit(1);
  392. }
  393. argv[0] = "sh";
  394. argv[1] = "-c";
  395. argv[2] = cmdline;
  396. argv[3] = NULL;
  397. execvp(argv[0], &argv[0]);
  398. kill(parent, SIGCHLD);
  399. exit(1);
  400. }
  401. }
  402. void suicide(const char *msg)
  403. {
  404. char tmp[512] = "";
  405. putlog(LOG_WARN, "*", STR("Comitting suicide: %s"), msg);
  406. simple_snprintf(tmp, sizeof(tmp), STR("Suicide: %s"), msg);
  407. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  408. if (!conf.bot->hub) {
  409. nuke_server(STR("kill the infidels!"));
  410. sleep(1);
  411. } else {
  412. unlink(userfile);
  413. simple_snprintf(tmp, sizeof(tmp), STR("%s~new"), userfile);
  414. unlink(tmp);
  415. simple_snprintf(tmp, sizeof(tmp), STR("%s~"), userfile);
  416. unlink(tmp);
  417. simple_snprintf(tmp, sizeof(tmp), STR("%s/%s~"), conf.datadir, userfile);
  418. unlink(tmp);
  419. simple_snprintf(tmp, sizeof(tmp), STR("%s/.u.0"), conf.datadir);
  420. unlink(tmp);
  421. simple_snprintf(tmp, sizeof(tmp), STR("%s/.u.1"), conf.datadir);
  422. unlink(tmp);
  423. }
  424. unlink(binname);
  425. if (conf.bot->localhub) {
  426. conf_checkpids(conf.bots);
  427. conf_killbot(conf.bots, NULL, NULL, SIGKILL);
  428. }
  429. unlink(conf.bot->pid_file);
  430. //Not recursively clearing these dirs as they may be ~USER/ ..
  431. unlink(conf.datadir); //Probably will fail, shrug
  432. unlink(tempdir); //Probably will fail too, oh well
  433. #ifndef CYGWIN_HACKS
  434. crontab_del();
  435. #endif /* !CYGWIN_HACKS */
  436. fatal(msg, 0);
  437. }
  438. void detected(int code, const char *msg)
  439. {
  440. char tmp[512] = "";
  441. struct flag_record fr = { FR_GLOBAL, 0, 0, 0 };
  442. int act = DET_WARN, do_fatal = 0, killbots = 0;
  443. if (code == DETECT_LOGIN)
  444. act = login;
  445. if (code == DETECT_TRACE)
  446. act = trace;
  447. if (code == DETECT_PROMISC)
  448. act = promisc;
  449. if (code == DETECT_HIJACK)
  450. act = hijack;
  451. switch (act) {
  452. case DET_IGNORE:
  453. break;
  454. case DET_WARN:
  455. putlog(LOG_WARN, "*", "%s", msg);
  456. break;
  457. case DET_REJECT:
  458. do_fork();
  459. putlog(LOG_WARN, "*", STR("Setting myself +d: %s"), msg);
  460. simple_snprintf(tmp, sizeof(tmp), "+d: %s", msg);
  461. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  462. fr.global = USER_DEOP;
  463. fr.bot = 1;
  464. set_user_flagrec(conf.bot->u, &fr, 0);
  465. sleep(1);
  466. break;
  467. case DET_DIE:
  468. putlog(LOG_WARN, "*", STR("Dying: %s"), msg);
  469. simple_snprintf(tmp, sizeof(tmp), STR("Dying: %s"), msg);
  470. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  471. if (!conf.bot->hub)
  472. nuke_server(STR("BBL"));
  473. sleep(1);
  474. killbots++;
  475. do_fatal++;
  476. break;
  477. case DET_SUICIDE:
  478. suicide(msg);
  479. break;
  480. }
  481. if (killbots && conf.bot->localhub) {
  482. conf_checkpids(conf.bots);
  483. conf_killbot(conf.bots, NULL, NULL, SIGKILL);
  484. }
  485. if (do_fatal)
  486. fatal(msg, 0);
  487. }
  488. const char *werr_tostr(int errnum)
  489. {
  490. switch (errnum) {
  491. case ERR_BINSTAT:
  492. return STR("Cannot access binary");
  493. case ERR_BADPASS:
  494. return STR("Incorrect password");
  495. case ERR_PASSWD:
  496. return STR("Cannot access the global passwd file");
  497. case ERR_WRONGBINDIR:
  498. return STR("Wrong directory/binary name");
  499. case ERR_DATADIR:
  500. return STR("Cannot access datadir.");
  501. case ERR_TMPSTAT:
  502. return STR("Cannot access tmp directory.");
  503. case ERR_TMPMOD:
  504. return STR("Cannot chmod() tmp directory.");
  505. case ERR_WRONGUID:
  506. return STR("UID in binary does not match geteuid()");
  507. case ERR_WRONGUNAME:
  508. return STR("Uname in binary does not match uname()");
  509. case ERR_BADCONF:
  510. return STR("Config file is incomplete");
  511. case ERR_BADBOT:
  512. return STR("No such botnick");
  513. case ERR_BOTDISABLED:
  514. return STR("Bot is disabled, remove '/' in config");
  515. case ERR_NOBOTS:
  516. return STR("There are no bots in the binary! Please use ./binary -C to edit");
  517. case ERR_NOHOMEDIR:
  518. return STR("There is no homedir set. Please set one in the binary config with ./binary -C");
  519. case ERR_NOUSERNAME:
  520. return STR("There is no username set. Please set one in the binary config with ./binary -C");
  521. case ERR_NOBOT:
  522. return STR("I have no bot record but received -B???");
  523. case ERR_NOTINIT:
  524. return STR("Binary data is not initialized; try ./binary -C");
  525. default:
  526. return STR("Unforseen error");
  527. }
  528. }
  529. void werr(int errnum)
  530. {
  531. /* [1]+ Done ls --color=auto -A -CF
  532. [1]+ Killed bash
  533. */
  534. /*
  535. int x = 0;
  536. unsigned long job = randint(2) + 1; */
  537. /* printf("[%lu] %lu%lu%lu%lu%lu\n", job, randint(2) + 1, randint(8) + 1, randint(8) + 1, errnum); */
  538. /* printf("\n[%lu]+ Killed rm -rf /\r\n", job); */
  539. /*
  540. if (checkedpass) {
  541. printf("[%lu] %d\n", job, getpid());
  542. }
  543. */
  544. /* printf("\n[%lu]+ Stopped %s\r\n", job, basename(binname)); */
  545. #ifdef OBSCURE_ERRORS
  546. sdprintf(STR("Error %d: %s"), errnum, werr_tostr(errnum));
  547. printf(STR("*** Error code %d\n\n"), errnum);
  548. printf(STR("Segmentation fault\n"));
  549. #else
  550. printf(STR("Error %d: %s\n"), errnum, werr_tostr(errnum));
  551. #endif
  552. fatal("", 0);
  553. exit(0); //gcc is stupid :)
  554. }
  555. int email(char *subject, char *msg, int who)
  556. {
  557. struct utsname un;
  558. char run[2048] = "", addrs[100] = "";
  559. bool mail = 0, sendmail = 0;
  560. FILE *f = NULL;
  561. uname(&un);
  562. if (is_file(STR("/usr/sbin/sendmail")))
  563. sendmail = 1;
  564. else if (is_file(STR("/usr/bin/mail")))
  565. mail = 1;
  566. else {
  567. putlog(LOG_WARN, "*", STR("I Have no usable mail client."));
  568. return 1;
  569. }
  570. if (who & EMAIL_OWNERS)
  571. strlcpy(addrs, replace(settings.owneremail, ",", " "), sizeof(addrs));
  572. if (sendmail)
  573. strlcpy(run, STR("/usr/sbin/sendmail -t"), sizeof(run));
  574. else if (mail)
  575. simple_snprintf(run, sizeof(run), STR("/usr/bin/mail %s -a \"From: %s@%s\" -s \"%s\" -a \"Content-Type: text/plain\""), addrs, conf.bot->nick ? conf.bot->nick : "none", un.nodename, subject);
  576. if ((f = popen(run, "w"))) {
  577. if (sendmail) {
  578. fprintf(f, STR("To: %s\n"), addrs);
  579. fprintf(f, STR("From: %s@%s\n"), origbotname[0] ? origbotname : (conf.username ? conf.username : "WRAITH"), un.nodename);
  580. fprintf(f, STR("Subject: %s\n"), subject);
  581. fprintf(f, STR("Content-Type: text/plain\n"));
  582. }
  583. fprintf(f, "%s\n", msg);
  584. if (fflush(f))
  585. return 1;
  586. if (pclose(f))
  587. return 1;
  588. } else
  589. return 1;
  590. return 0;
  591. }
  592. void baduname(char *confhas, char *myuname) {
  593. char *tmpFile = NULL;
  594. int tosend = 0, make = 0;
  595. size_t siz = strlen(tempdir) + 3 + 1;
  596. tmpFile = (char *) my_calloc(1, siz);
  597. simple_snprintf(tmpFile, siz, STR("%s/.un"), conf.datadir);
  598. if (is_file(tmpFile)) {
  599. struct stat ss;
  600. time_t diff;
  601. stat(tmpFile, &ss);
  602. diff = now - ss.st_mtime;
  603. if (diff >= 86400) {
  604. tosend++; /* only send once a day */
  605. unlink(tmpFile); /* remove file */
  606. make++; /* make a new one at thie time. */
  607. }
  608. } else {
  609. make++;
  610. }
  611. if (make) {
  612. FILE *fp = NULL;
  613. if ((fp = fopen(tmpFile, "w"))) {
  614. fprintf(fp, "\n");
  615. fflush(fp);
  616. fclose(fp);
  617. tosend++; /* only send if we could write the file. */
  618. }
  619. }
  620. if (tosend) {
  621. struct utsname un;
  622. char msg[1024] = "", subject[31] = "";
  623. uname(&un);
  624. simple_snprintf(subject, sizeof subject, STR("CONF/UNAME() mismatch notice"));
  625. simple_snprintf(msg, sizeof msg, STR("This is an auto email from a wraith bot which has you in it's OWNER_EMAIL list..\n \nThe uname() output on this box has changed, probably due to a kernel upgrade...\nMy login is: %s\nMy binary is: %s\nLocalhub: %s\nConf : %s\nUname(): %s\n \nThis email will only be sent once a day while this error is present.\nYou need to login to my shell (%s) and fix my local config.\n"),
  626. conf.username ? conf.username : "unknown",
  627. binname,
  628. conf.bots && conf.bots->nick ? conf.bots->nick : origbotname,
  629. confhas, myuname, un.nodename);
  630. email(subject, msg, EMAIL_OWNERS);
  631. }
  632. free(tmpFile);
  633. }
  634. char *homedir(bool useconf)
  635. {
  636. static char homedir_buf[DIRMAX] = "";
  637. if (!homedir_buf[0]) {
  638. char tmp[DIRMAX] = "";
  639. if (conf.homedir && useconf)
  640. simple_snprintf(tmp, sizeof tmp, "%s", conf.homedir);
  641. else {
  642. #ifdef CYGWIN_HACKS
  643. simple_snprintf(tmp, sizeof tmp, "%s", dirname(binname));
  644. #else /* !CYGWIN_HACKS */
  645. struct passwd *pw = NULL;
  646. ContextNote(STR("getpwuid()"));
  647. pw = getpwuid(myuid);
  648. if (pw)
  649. simple_snprintf(tmp, sizeof tmp, "%s", pw->pw_dir);
  650. ContextNote(STR("getpwuid(): Success"));
  651. #endif /* CYGWIN_HACKS */
  652. }
  653. ContextNote(STR("realpath()"));
  654. if (tmp[0])
  655. realpath(tmp, homedir_buf); /* this will convert lame home dirs of /home/blah->/usr/home/blah */
  656. ContextNote(STR("realpath(): Success"));
  657. }
  658. return homedir_buf[0] ? homedir_buf : NULL;
  659. }
  660. char *my_username()
  661. {
  662. static char username[DIRMAX] = "";
  663. if (!username[0]) {
  664. #ifdef CYGWIN_HACKS
  665. simple_snprintf(username, sizeof username, "cygwin");
  666. #else /* !CYGWIN_HACKS */
  667. struct passwd *pw = NULL;
  668. ContextNote(STR("getpwuid()"));
  669. pw = getpwuid(myuid);
  670. ContextNote(STR("getpwuid(): Success"));
  671. if (pw)
  672. strlcpy(username, pw->pw_name, sizeof(username));
  673. #endif /* CYGWIN_HACKS */
  674. }
  675. return username[0] ? username : NULL;
  676. }
  677. int mkdir_p(const char *dir) {
  678. char *p = NULL, *path = NULL;
  679. path = p = strdup(dir);
  680. do {
  681. p = strchr(p + 1, '/');
  682. if (p)
  683. *p = '\0';
  684. if (can_stat(path) && !is_dir(path))
  685. unlink(path);
  686. if (!can_stat(path)) {
  687. if (mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR)) {
  688. unlink(path);
  689. mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR);
  690. }
  691. }
  692. if (p)
  693. *p = '/';
  694. } while(p);
  695. int couldStat = can_stat(path);
  696. free(path);
  697. return couldStat;
  698. }
  699. void expand_tilde(char **ptr)
  700. {
  701. if (!conf.homedir || !conf.homedir[0])
  702. return;
  703. char *str = ptr ? *ptr : NULL;
  704. if (str && strchr(str, '~')) {
  705. char *p = NULL;
  706. size_t siz = strlen(str);
  707. if (str[siz - 1] == '/')
  708. str[siz - 1] = 0;
  709. if ((p = replace(str, "~", conf.homedir)))
  710. str_redup(ptr, p);
  711. else
  712. fatal("Unforseen error expanding '~'", 0);
  713. }
  714. }
  715. char *my_uname()
  716. {
  717. static char os_uname[250] = "";
  718. if (!os_uname[0]) {
  719. char *unix_n = NULL, *vers_n = NULL;
  720. struct utsname un;
  721. if (uname(&un) < 0) {
  722. unix_n = "*unkown*";
  723. vers_n = "";
  724. } else {
  725. unix_n = un.nodename;
  726. #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
  727. vers_n = un.release;
  728. #elif defined(__linux__)
  729. vers_n = un.version;
  730. #else
  731. # error "Don't know how to handle uname for this system!"
  732. #endif
  733. }
  734. simple_snprintf(os_uname, sizeof os_uname, "%s %s", unix_n, vers_n);
  735. }
  736. return os_uname;
  737. }
  738. #ifndef CYGWIN_HACKS
  739. char *move_bin(const char *ipath, const char *file, bool run)
  740. {
  741. char *path = strdup(ipath);
  742. expand_tilde(&path);
  743. /* move the binary to the correct place */
  744. static char newbin[DIRMAX] = "";
  745. char real[DIRMAX] = "";
  746. simple_snprintf(newbin, sizeof newbin, "%s%s%s", path, path[strlen(path) - 1] == '/' ? "" : "/", file);
  747. ContextNote(STR("realpath()"));
  748. realpath(binname, real); /* get the realpath of binname */
  749. ContextNote(STR("realpath(): Success"));
  750. /* running from wrong dir, or wrong bin name.. lets try to fix that :) */
  751. sdprintf(STR("binname: %s"), binname);
  752. sdprintf(STR("newbin: %s"), newbin);
  753. sdprintf(STR("real: %s"), real);
  754. if (strcmp(binname, newbin) && strcmp(newbin, real)) { /* if wrong path and new path != current */
  755. bool ok = 1;
  756. sdprintf(STR("wrong dir, is: %s :: %s"), binname, newbin);
  757. unlink(newbin);
  758. if (copyfile(binname, newbin))
  759. ok = 0;
  760. if (ok && !can_stat(newbin)) {
  761. unlink(newbin);
  762. ok = 0;
  763. }
  764. if (ok && fixmod(newbin)) {
  765. unlink(newbin);
  766. ok = 0;
  767. }
  768. if (ok) {
  769. sdprintf(STR("Binary successfully moved to: %s"), newbin);
  770. unlink(binname);
  771. if (run) {
  772. simple_snprintf(newbin, sizeof newbin, "%s%s%s",
  773. path, path[strlen(path) - 1] == '/' ? "" : "/", shell_escape(file));
  774. system(newbin);
  775. sdprintf(STR("exiting to let new binary run..."));
  776. exit(0);
  777. }
  778. } else {
  779. if (run)
  780. werr(ERR_WRONGBINDIR);
  781. sdprintf(STR("Binary move failed to: %s"), newbin);
  782. return binname;
  783. }
  784. }
  785. return newbin;
  786. }
  787. void check_crontab()
  788. {
  789. int i = 0;
  790. if (!conf.bot->hub && !conf.bot->localhub)
  791. fatal(STR("something is wrong."), 0);
  792. if (!(i = crontab_exists())) {
  793. crontab_create(5);
  794. if (!(i = crontab_exists()))
  795. printf(STR("* Error writing crontab entry.\n"));
  796. }
  797. }
  798. void crontab_del() {
  799. char *tmpFile = NULL, *p = NULL, buf[2048] = "";
  800. size_t tmplen = strlen(binname) + 100;
  801. tmpFile = (char *) my_calloc(1, tmplen);
  802. strlcpy(tmpFile, shell_escape(binname), tmplen);
  803. if (!(p = strrchr(tmpFile, '/')))
  804. return;
  805. p++;
  806. strcpy(p, STR(".ctb"));
  807. simple_snprintf(buf, sizeof(buf), STR("crontab -l | grep -v '%s' | grep -v \"^#\" | grep -v \"^\\$\" > %s"), binname, tmpFile);
  808. if (shell_exec(buf, NULL, NULL, NULL)) {
  809. simple_snprintf(buf, sizeof(buf), STR("crontab %s"), tmpFile);
  810. shell_exec(buf, NULL, NULL, NULL);
  811. }
  812. unlink(tmpFile);
  813. }
  814. int crontab_exists() {
  815. char buf[2048] = "", *out = NULL;
  816. simple_snprintf(buf, sizeof buf, STR("crontab -l | grep '%s' | grep -v \"^#\""), binname);
  817. if (shell_exec(buf, NULL, &out, NULL)) {
  818. if (out && strstr(out, binname)) {
  819. free(out);
  820. return 1;
  821. } else {
  822. if (out)
  823. free(out);
  824. return 0;
  825. }
  826. } else
  827. return (-1);
  828. }
  829. char s1_2[3] = "",s1_8[3] = "",s2_5[3] = "";
  830. void crontab_create(int interval) {
  831. char tmpFile[161] = "";
  832. FILE *f = NULL;
  833. int fd;
  834. simple_snprintf(tmpFile, sizeof tmpFile, STR("%s.crontab-XXXXXX"), tempdir);
  835. if ((fd = mkstemp(tmpFile)) == -1) {
  836. unlink(tmpFile);
  837. return;
  838. }
  839. char buf[256] = "";
  840. simple_snprintf(buf, sizeof buf, STR("crontab -l | grep -v \"%s\" | grep -v \"^#\" | grep -v \"^\\$\"> %s"),
  841. binname, tmpFile);
  842. if (shell_exec(buf, NULL, NULL, NULL) && (f = fdopen(fd, "a")) != NULL) {
  843. buf[0] = 0;
  844. if (interval == 1)
  845. strlcpy(buf, "*", 2);
  846. else {
  847. int i = 1;
  848. int si = randint(interval);
  849. while (i < 60) {
  850. if (buf[0])
  851. strlcat(buf, ",", sizeof(buf));
  852. simple_snprintf(&buf[strlen(buf)], sizeof(buf) - strlen(buf), "%i", (i + si) % 60);
  853. i += interval;
  854. }
  855. }
  856. simple_snprintf(buf + strlen(buf), sizeof buf, STR(" * * * * %s > /dev/null 2>&1"), binname);
  857. fseek(f, 0, SEEK_END);
  858. fprintf(f, "\n%s\n", buf);
  859. fclose(f);
  860. simple_snprintf(buf, sizeof(buf), STR("crontab %s"), tmpFile);
  861. shell_exec(buf, NULL, NULL, NULL);
  862. }
  863. close(fd);
  864. unlink(tmpFile);
  865. }
  866. #endif /* !CYGWIN_HACKS */
  867. int det_translate(const char *word)
  868. {
  869. if (word && word[0]) {
  870. if (!egg_strcasecmp(word, STR("ignore")))
  871. return DET_IGNORE;
  872. else if (!egg_strcasecmp(word, STR("warn")))
  873. return DET_WARN;
  874. else if (!egg_strcasecmp(word, STR("reject")))
  875. return DET_REJECT;
  876. else if (!egg_strcasecmp(word, STR("die")))
  877. return DET_DIE;
  878. else if (!egg_strcasecmp(word, STR("suicide")))
  879. return DET_SUICIDE;
  880. }
  881. return DET_IGNORE;
  882. }
  883. const char *det_translate_num(int num)
  884. {
  885. switch (num) {
  886. case DET_IGNORE: return STR("ignore");
  887. case DET_WARN: return STR("warn");
  888. case DET_REJECT: return STR("reject");
  889. case DET_DIE: return STR("die");
  890. case DET_SUICIDE:return STR("suicide");
  891. default: return STR("ignore");
  892. }
  893. return STR("ignore");
  894. }
  895. char *shell_escape(const char *path)
  896. {
  897. static char ret1[DIRMAX] = "", ret2[DIRMAX] = "", *ret = NULL;
  898. static bool alt = 0;
  899. char *c = NULL;
  900. if (alt) {
  901. alt = 0;
  902. ret = ret1;
  903. } else {
  904. alt = 1;
  905. ret = ret2;
  906. }
  907. ret[0] = 0;
  908. for (c = (char *) path; c && *c; ++c) {
  909. if (strchr(ESCAPESHELL, *c))
  910. simple_snprintf(&ret[strlen(ret)], sizeof(ret1) - strlen(ret), "\\%c", *c);
  911. else
  912. simple_snprintf(&ret[strlen(ret)], sizeof(ret1) - strlen(ret), "%c", *c);
  913. }
  914. return ret;
  915. }