shell.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. /*
  2. * Copyright (C) 1997 Robey Pointer
  3. * Copyright (C) 1999 - 2002 Eggheads Development Team
  4. * Copyright (C) 2002 - 2010 Bryan Drewery
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  19. */
  20. /*
  21. * shell.c -- handles:
  22. *
  23. * All shell related functions
  24. * -shell_exec()
  25. * -botconfig parsing
  26. * -check_*()
  27. * -crontab functions
  28. *
  29. */
  30. #include "common.h"
  31. #include "shell.h"
  32. #include "chanprog.h"
  33. #include "set.h"
  34. #include "settings.h"
  35. #include "userrec.h"
  36. #include "net.h"
  37. #include "flags.h"
  38. #include "tandem.h"
  39. #include "main.h"
  40. #include "dccutil.h"
  41. #include "misc.h"
  42. #include "misc_file.h"
  43. #include "bg.h"
  44. #include "stat.h"
  45. #include "users.h"
  46. #include "botnet.h"
  47. #include "src/mod/server.mod/server.h"
  48. #include <bdlib/src/String.h>
  49. #include <bdlib/src/Stream.h>
  50. #include <sys/types.h>
  51. #include <pwd.h>
  52. #include <signal.h>
  53. #ifdef HAVE_SYS_PTRACE_H
  54. # include <sys/ptrace.h>
  55. #endif /* HAVE_SYS_PTRACE_H */
  56. #include <sys/wait.h>
  57. #include <sys/utsname.h>
  58. #include <pwd.h>
  59. #include <errno.h>
  60. #include <net/if.h>
  61. #include <sys/ioctl.h>
  62. #include <sys/socket.h>
  63. #include <ctype.h>
  64. #include <fcntl.h>
  65. #include <sys/stat.h>
  66. #include <unistd.h>
  67. #include <dirent.h>
  68. bool clear_tmpdir = 0;
  69. void clear_tmp()
  70. {
  71. if (!clear_tmpdir)
  72. return;
  73. DIR *tmp = NULL;
  74. if (!(tmp = opendir(tempdir)))
  75. return;
  76. struct dirent *dir_ent = NULL;
  77. char *file = NULL;
  78. size_t flen = 0;
  79. while ((dir_ent = readdir(tmp))) {
  80. if (strncmp(dir_ent->d_name, ".pid.", 4) &&
  81. strncmp(dir_ent->d_name, ".u", 2) &&
  82. strcmp(dir_ent->d_name, ".bin.old") &&
  83. strncmp(dir_ent->d_name, STR(".socks-"), 7) &&
  84. strcmp(dir_ent->d_name, ".") &&
  85. strcmp(dir_ent->d_name, "..")) {
  86. flen = strlen(dir_ent->d_name) + strlen(tempdir) + 1;
  87. file = (char *) my_calloc(1, flen);
  88. strlcat(file, tempdir, flen);
  89. strlcat(file, dir_ent->d_name, flen);
  90. file[strlen(file)] = 0;
  91. sdprintf("clear_tmp: %s", file);
  92. unlink(file);
  93. free(file);
  94. }
  95. }
  96. closedir(tmp);
  97. return;
  98. }
  99. void check_maxfiles()
  100. {
  101. int sock = -1, sock1 = -1 , bogus = 0, failed_close = 0;
  102. #ifdef USE_IPV6
  103. sock1 = getsock(0, AF_INET); /* fill up any lower avail */
  104. sock = getsock(0, AF_INET);
  105. #else
  106. sock1 = getsock(0);
  107. sock = getsock(0);
  108. #endif
  109. if (sock1 != -1)
  110. killsock(sock1);
  111. if (sock == -1) {
  112. return;
  113. } else
  114. killsock(sock);
  115. bogus = sock - socks_total - 4; //4 for stdin/stdout/stderr/dns
  116. if (unlikely(bogus >= 50)) { /* Attempt to close them */
  117. sdprintf("SOCK: %d BOGUS: %d SOCKS_TOTAL: %d", sock, bogus, socks_total);
  118. for (int i = 10; i < sock; i++) /* dont close lower sockets, they're probably legit */
  119. if (!findanysnum(i)) {
  120. if ((close(i)) == -1) /* try to close the BOGUS fd (likely a KQUEUE) */
  121. failed_close++;
  122. else
  123. bogus--;
  124. }
  125. if (bogus >= 150 || failed_close >= 50) {
  126. if (tands > 0) {
  127. botnet_send_chat(-1, conf.bot->nick, "Max FD reached, restarting...");
  128. botnet_send_bye("Max FD reached, restarting...");
  129. }
  130. nuke_server("brb");
  131. cycle_time = 0;
  132. restart(-1);
  133. } else if (bogus >= 100 && (bogus % 10) == 0) {
  134. putlog(LOG_WARN, "*", "* WARNING: $b%d$b bogus file descriptors detected, auto restart at 150", bogus);
  135. }
  136. }
  137. }
  138. void check_mypid()
  139. {
  140. pid_t pid = 0;
  141. if (can_stat(conf.bot->pid_file))
  142. pid = checkpid(conf.bot->nick, NULL);
  143. if (pid && (pid != getpid()))
  144. fatal(STR("getpid() does not match pid in file. Possible cloned process, exiting.."), 0);
  145. }
  146. char last_buf[128] = "";
  147. void check_last() {
  148. if (login == DET_IGNORE)
  149. return;
  150. if (conf.username) {
  151. char *out = NULL, buf[50] = "";
  152. simple_snprintf(buf, sizeof(buf), STR("last -10 %s"), conf.username);
  153. if (shell_exec(buf, NULL, &out, NULL, 1)) {
  154. if (out) {
  155. char *p = NULL;
  156. p = strchr(out, '\n');
  157. if (p)
  158. *p = 0;
  159. if (strlen(out) > 10) {
  160. if (last_buf[0]) {
  161. if (strncmp(last_buf, out, sizeof(last_buf))) {
  162. char *work = NULL;
  163. size_t siz = strlen(out) + 7 + 2 + 1;
  164. work = (char *) my_calloc(1, siz);
  165. simple_snprintf(work, siz, STR("Login: %s"), out);
  166. detected(DETECT_LOGIN, work);
  167. free(work);
  168. }
  169. }
  170. strlcpy(last_buf, out, sizeof(last_buf));
  171. }
  172. free(out);
  173. }
  174. }
  175. }
  176. }
  177. void check_promisc()
  178. {
  179. #ifdef SIOCGIFCONF
  180. if (promisc == DET_IGNORE)
  181. return;
  182. int sock = socket(AF_INET, SOCK_DGRAM, 0);
  183. if (sock < 0)
  184. return;
  185. struct ifconf ifcnf;
  186. char buf[1024] = "";
  187. ifcnf.ifc_len = sizeof(buf);
  188. ifcnf.ifc_buf = buf;
  189. if (ioctl(sock, SIOCGIFCONF, &ifcnf) < 0) {
  190. close(sock);
  191. return;
  192. }
  193. char *reqp = NULL, *end_req = NULL;
  194. reqp = buf; /* pointer to start of array */
  195. end_req = buf + ifcnf.ifc_len; /* pointer to end of array */
  196. while (reqp < end_req) {
  197. struct ifreq ifreq, *ifr = NULL;
  198. ifr = (struct ifreq *) reqp; /* start examining interface */
  199. ifreq = *ifr;
  200. if (!ioctl(sock, SIOCGIFFLAGS, &ifreq)) { /* we can read this interface! */
  201. /* sdprintf("Examing interface: %s", ifr->ifr_name); */
  202. if (unlikely(ifreq.ifr_flags & IFF_PROMISC) && strncmp(ifr->ifr_name, "pflog", 5) && strncmp(ifr->ifr_name, "ipfw", 4)) {
  203. char which[101] = "";
  204. simple_snprintf(which, sizeof(which), STR("Detected promiscuous mode on interface: %s"), ifr->ifr_name);
  205. ioctl(sock, SIOCSIFFLAGS, &ifreq); /* set flags */
  206. detected(DETECT_PROMISC, which);
  207. break;
  208. }
  209. }
  210. /* move pointer to next array element (next interface) */
  211. reqp += sizeof(ifr->ifr_name) + sizeof(ifr->ifr_addr);
  212. }
  213. close(sock);
  214. #endif /* SIOCGIFCONF */
  215. }
  216. bool traced = 0;
  217. static void got_sigtrap(int z)
  218. {
  219. traced = 0;
  220. }
  221. void check_trace(int start)
  222. {
  223. if (trace == DET_IGNORE || trace == DET_WARN)
  224. trace = DET_DIE;
  225. // return;
  226. #ifdef DEBUG
  227. trace = DET_IGNORE;
  228. #endif /* DEBUG */
  229. if (trace == DET_IGNORE)
  230. return;
  231. pid_t parent = getpid();
  232. /* we send ourselves a SIGTRAP, if we recieve, we're not being traced, otherwise we are. */
  233. signal(SIGTRAP, got_sigtrap);
  234. traced = 1;
  235. raise(SIGTRAP);
  236. /* no longer need this__asm__("INT3"); //SIGTRAP */
  237. signal(SIGTRAP, SIG_DFL);
  238. if (!traced) {
  239. signal(SIGINT, got_sigtrap);
  240. traced = 1;
  241. raise(SIGINT);
  242. signal(SIGINT, SIG_DFL);
  243. }
  244. if (traced) {
  245. if (start) {
  246. kill(parent, SIGKILL);
  247. exit(1);
  248. } else
  249. detected(DETECT_TRACE, STR("I'm being traced!"));
  250. } else {
  251. if (!start)
  252. return;
  253. #ifndef __sun__
  254. int x, i;
  255. /* now, let's attempt to ptrace ourself */
  256. switch ((x = fork())) {
  257. case -1:
  258. return;
  259. case 0: //child
  260. i = ptrace(PT_ATTACH, parent, 0, 0);
  261. /* EPERM is given on fbsd when security.bsd.unprivileged_proc_debug=0 */
  262. if (i == -1 && errno != EPERM && errno != EINVAL) {
  263. if (start) {
  264. kill(parent, SIGKILL);
  265. exit(1);
  266. } else
  267. detected(DETECT_TRACE, STR("I'm being traced!"));
  268. } else {
  269. waitpid(parent, NULL, 0);
  270. ptrace(PT_DETACH, parent, (char *) 1, 0);
  271. kill(parent, SIGCHLD);
  272. }
  273. exit(0);
  274. default: //parent
  275. waitpid(x, NULL, 0);
  276. }
  277. #endif
  278. }
  279. }
  280. int shell_exec(char *cmdline, char *input, char **output, char **erroutput, bool simple)
  281. {
  282. if (!cmdline)
  283. return 0;
  284. Tempfile *in = NULL, *out = NULL, *err = NULL;
  285. int x;
  286. int parent = getpid();
  287. /* Set up temp files */
  288. in = new Tempfile("in");
  289. if (!in || in->error) {
  290. // putlog(LOG_ERRORS, "*" , "exec: Couldn't open '%s': %s", in->file, strerror(errno));
  291. if (in)
  292. delete in;
  293. return 0;
  294. }
  295. if (input) {
  296. if (fwrite(input, strlen(input), 1, in->f) != 1) {
  297. // putlog(LOG_ERRORS, "*", "exec: Couldn't write to '%s': %s", in->file, strerror(errno));
  298. delete in;
  299. return 0;
  300. }
  301. fseek(in->f, 0, SEEK_SET);
  302. }
  303. err = new Tempfile("err");
  304. if (!err || err->error) {
  305. // putlog(LOG_ERRORS, "*", "exec: Couldn't open '%s': %s", err->file, strerror(errno));
  306. delete in;
  307. if (err)
  308. delete err;
  309. return 0;
  310. }
  311. out = new Tempfile("out");
  312. if (!out || out->error) {
  313. // putlog(LOG_ERRORS, "*", "exec: Couldn't open '%s': %s", out->file, strerror(errno));
  314. delete in;
  315. delete err;
  316. if (out)
  317. delete out;
  318. return 0;
  319. }
  320. x = fork();
  321. if (x == -1) {
  322. putlog(LOG_ERRORS, "*", "exec: fork() failed: %s", strerror(errno));
  323. delete in;
  324. delete err;
  325. delete out;
  326. return 0;
  327. }
  328. if (x) { /* Parent: wait for the child to complete */
  329. int st = 0;
  330. size_t fs = 0;
  331. waitpid(x, &st, 0);
  332. /* child is now complete, read the files into buffers */
  333. delete in;
  334. fflush(out->f);
  335. fflush(err->f);
  336. if (erroutput) {
  337. char *buf = NULL;
  338. fseek(err->f, 0, SEEK_END);
  339. fs = ftell(err->f);
  340. if (fs == 0) {
  341. (*erroutput) = NULL;
  342. } else {
  343. buf = (char *) my_calloc(1, fs + 1);
  344. fseek(err->f, 0, SEEK_SET);
  345. if (!fread(buf, 1, fs, err->f))
  346. fs = 0;
  347. buf[fs] = 0;
  348. (*erroutput) = buf;
  349. }
  350. }
  351. delete err;
  352. if (output) {
  353. char *buf = NULL;
  354. fseek(out->f, 0, SEEK_END);
  355. fs = ftell(out->f);
  356. if (fs == 0) {
  357. (*output) = NULL;
  358. } else {
  359. buf = (char *) my_calloc(1, fs + 1);
  360. fseek(out->f, 0, SEEK_SET);
  361. if (!fread(buf, 1, fs, out->f))
  362. fs = 0;
  363. buf[fs] = 0;
  364. (*output) = buf;
  365. }
  366. }
  367. delete out;
  368. return 1;
  369. } else {
  370. /* Child: make fd's and set them up as std* */
  371. // int ind, outd, errd;
  372. // ind = fileno(inpFile);
  373. // outd = fileno(outFile);
  374. // errd = fileno(errFile);
  375. if (dup2(in->fd, STDIN_FILENO) == (-1)) {
  376. kill(parent, SIGCHLD);
  377. exit(1);
  378. }
  379. if (dup2(out->fd, STDOUT_FILENO) == (-1)) {
  380. kill(parent, SIGCHLD);
  381. exit(1);
  382. }
  383. if (dup2(err->fd, STDERR_FILENO) == (-1)) {
  384. kill(parent, SIGCHLD);
  385. exit(1);
  386. }
  387. // Close all sockets
  388. for (int fd = 3; fd < MAX_SOCKETS; ++fd) close(fd);
  389. char *argv[15];
  390. if (simple) {
  391. char *p = NULL;
  392. int n = 0;
  393. char *mycmdline = strdup(cmdline);
  394. while (mycmdline[0] && (p = newsplit(&mycmdline)))
  395. argv[n++] = p;
  396. argv[n] = NULL;
  397. } else {
  398. argv[0] = "/bin/sh";
  399. argv[1] = "-c";
  400. argv[2] = cmdline;
  401. argv[3] = NULL;
  402. }
  403. execvp(argv[0], &argv[0]);
  404. kill(parent, SIGCHLD);
  405. exit(1);
  406. }
  407. }
  408. int simple_exec(const char* argv[]) {
  409. pid_t pid, savedpid;
  410. int status;
  411. switch ((pid = fork())) {
  412. case -1:
  413. break;
  414. case 0: //child
  415. // Close all sockets
  416. for (int fd = 3; fd < MAX_SOCKETS; ++fd) close(fd);
  417. execvp(argv[0], (char* const*) &argv[0]);
  418. _exit(127);
  419. default: //parent
  420. savedpid = pid;
  421. do {
  422. pid = wait4(savedpid, &status, 0, (struct rusage *)0);
  423. } while (pid == -1 && errno == EINTR);
  424. break;
  425. }
  426. return(pid == -1 ? -1 : status);
  427. }
  428. void suicide(const char *msg)
  429. {
  430. char tmp[512] = "";
  431. putlog(LOG_WARN, "*", STR("Comitting suicide: %s"), msg);
  432. simple_snprintf(tmp, sizeof(tmp), STR("Suicide: %s"), msg);
  433. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  434. if (!conf.bot->hub) {
  435. nuke_server(STR("kill the infidels!"));
  436. sleep(1);
  437. } else {
  438. unlink(userfile);
  439. simple_snprintf(tmp, sizeof(tmp), STR("%s~new"), userfile);
  440. unlink(tmp);
  441. simple_snprintf(tmp, sizeof(tmp), STR("%s~"), userfile);
  442. unlink(tmp);
  443. simple_snprintf(tmp, sizeof(tmp), STR("%s/%s~"), conf.datadir, userfile);
  444. unlink(tmp);
  445. simple_snprintf(tmp, sizeof(tmp), STR("%s/.u.0"), conf.datadir);
  446. unlink(tmp);
  447. simple_snprintf(tmp, sizeof(tmp), STR("%s/.u.1"), conf.datadir);
  448. unlink(tmp);
  449. }
  450. unlink(binname);
  451. if (conf.bot->localhub) {
  452. conf_checkpids(conf.bots);
  453. conf_killbot(conf.bots, NULL, NULL, SIGKILL);
  454. }
  455. unlink(conf.bot->pid_file);
  456. //Not recursively clearing these dirs as they may be ~USER/ ..
  457. unlink(conf.datadir); //Probably will fail, shrug
  458. unlink(tempdir); //Probably will fail too, oh well
  459. crontab_del();
  460. fatal(msg, 0);
  461. }
  462. void detected(int code, const char *msg)
  463. {
  464. char tmp[512] = "";
  465. struct flag_record fr = { FR_GLOBAL, 0, 0, 0 };
  466. int act = DET_WARN, do_fatal = 0, killbots = 0;
  467. if (code == DETECT_LOGIN)
  468. act = login;
  469. if (code == DETECT_TRACE)
  470. act = trace;
  471. if (code == DETECT_PROMISC)
  472. act = promisc;
  473. if (code == DETECT_HIJACK)
  474. act = hijack;
  475. switch (act) {
  476. case DET_IGNORE:
  477. break;
  478. case DET_WARN:
  479. putlog(LOG_WARN, "*", "%s", msg);
  480. break;
  481. case DET_REJECT:
  482. do_fork();
  483. putlog(LOG_WARN, "*", STR("Setting myself +d: %s"), msg);
  484. simple_snprintf(tmp, sizeof(tmp), "+d: %s", msg);
  485. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  486. fr.global = USER_DEOP;
  487. fr.bot = 1;
  488. set_user_flagrec(conf.bot->u, &fr, 0);
  489. sleep(1);
  490. break;
  491. case DET_DIE:
  492. putlog(LOG_WARN, "*", STR("Dying: %s"), msg);
  493. simple_snprintf(tmp, sizeof(tmp), STR("Dying: %s"), msg);
  494. set_user(&USERENTRY_COMMENT, conf.bot->u, tmp);
  495. if (!conf.bot->hub)
  496. nuke_server(STR("BBL"));
  497. sleep(1);
  498. killbots++;
  499. do_fatal++;
  500. break;
  501. case DET_SUICIDE:
  502. suicide(msg);
  503. break;
  504. }
  505. if (killbots && conf.bot->localhub) {
  506. conf_checkpids(conf.bots);
  507. conf_killbot(conf.bots, NULL, NULL, SIGKILL);
  508. }
  509. if (do_fatal)
  510. fatal(msg, 0);
  511. }
  512. const char *werr_tostr(int errnum)
  513. {
  514. switch (errnum) {
  515. case ERR_BINSTAT:
  516. return STR("Cannot access binary");
  517. case ERR_BADPASS:
  518. return STR("Incorrect password");
  519. case ERR_PASSWD:
  520. return STR("Cannot access the global passwd file");
  521. case ERR_WRONGBINDIR:
  522. return STR("Wrong directory/binary name");
  523. case ERR_DATADIR:
  524. return STR("Cannot access datadir.");
  525. case ERR_TMPSTAT:
  526. return STR("Cannot access tmp directory.");
  527. case ERR_TMPMOD:
  528. return STR("Cannot chmod() tmp directory.");
  529. case ERR_WRONGUID:
  530. return STR("UID in binary does not match geteuid()");
  531. case ERR_WRONGUNAME:
  532. return STR("Uname in binary does not match uname()");
  533. case ERR_BADCONF:
  534. return STR("Config file is incomplete");
  535. case ERR_BADBOT:
  536. return STR("No such botnick");
  537. case ERR_BOTDISABLED:
  538. return STR("Bot is disabled, remove '/' in config");
  539. case ERR_NOBOTS:
  540. return STR("There are no bots in the binary! Please use ./binary -C to edit");
  541. case ERR_NOHOMEDIR:
  542. return STR("There is no homedir set. Please set one in the binary config with ./binary -C");
  543. case ERR_NOUSERNAME:
  544. return STR("There is no username set. Please set one in the binary config with ./binary -C");
  545. case ERR_NOBOT:
  546. return STR("I have no bot record but received -B???");
  547. case ERR_NOTINIT:
  548. return STR("Binary data is not initialized; try ./binary -C");
  549. default:
  550. return STR("Unforseen error");
  551. }
  552. }
  553. void werr(int errnum)
  554. {
  555. /* [1]+ Done ls --color=auto -A -CF
  556. [1]+ Killed bash
  557. */
  558. /*
  559. int x = 0;
  560. unsigned long job = randint(2) + 1; */
  561. /* printf("[%lu] %lu%lu%lu%lu%lu\n", job, randint(2) + 1, randint(8) + 1, randint(8) + 1, errnum); */
  562. /* printf("\n[%lu]+ Killed rm -rf /\r\n", job); */
  563. /*
  564. if (checkedpass) {
  565. printf("[%lu] %d\n", job, getpid());
  566. }
  567. */
  568. /* printf("\n[%lu]+ Stopped %s\r\n", job, basename(binname)); */
  569. #ifdef OBSCURE_ERRORS
  570. sdprintf(STR("Error %d: %s"), errnum, werr_tostr(errnum));
  571. printf(STR("*** Error code %d\n\n"), errnum);
  572. printf(STR("Segmentation fault\n"));
  573. #else
  574. printf(STR("Error %d: %s\n"), errnum, werr_tostr(errnum));
  575. #endif
  576. fatal("", 0);
  577. exit(0); //gcc is stupid :)
  578. }
  579. char *homedir(bool useconf)
  580. {
  581. static char homedir_buf[PATH_MAX] = "";
  582. if (!homedir_buf[0]) {
  583. if (conf.homedir && useconf)
  584. simple_snprintf(homedir_buf, sizeof homedir_buf, "%s", conf.homedir);
  585. else {
  586. char *home = getenv("HOME");
  587. if (home && strlen(home))
  588. strlcpy(homedir_buf, home, sizeof(homedir_buf));
  589. }
  590. }
  591. return homedir_buf[0] ? homedir_buf : NULL;
  592. }
  593. char *my_username()
  594. {
  595. static char username[DIRMAX] = "";
  596. if (!username[0]) {
  597. char *user = getenv("USER");
  598. if (user && strlen(user))
  599. strlcpy(username, user, sizeof(username));
  600. }
  601. return username[0] ? username : NULL;
  602. }
  603. int mkdir_p(const char *dir) {
  604. char *p = NULL, *path = NULL;
  605. path = p = strdup(dir);
  606. do {
  607. p = strchr(p + 1, '/');
  608. if (p)
  609. *p = '\0';
  610. if (can_stat(path) && !is_dir(path))
  611. unlink(path);
  612. if (!can_stat(path)) {
  613. if (mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR)) {
  614. unlink(path);
  615. mkdir(path, S_IRUSR | S_IWUSR | S_IXUSR);
  616. }
  617. }
  618. if (p)
  619. *p = '/';
  620. } while(p);
  621. int couldStat = can_stat(path);
  622. free(path);
  623. return couldStat;
  624. }
  625. void expand_tilde(char **ptr)
  626. {
  627. if (!conf.homedir || !conf.homedir[0])
  628. return;
  629. char *str = ptr ? *ptr : NULL;
  630. if (str && strchr(str, '~')) {
  631. char *p = NULL;
  632. size_t siz = strlen(str);
  633. if (str[siz - 1] == '/')
  634. str[siz - 1] = 0;
  635. if ((p = replace(str, "~", conf.homedir)))
  636. str_redup(ptr, p);
  637. else
  638. fatal("Unforseen error expanding '~'", 0);
  639. }
  640. }
  641. void check_crontab()
  642. {
  643. int i = 0;
  644. if (!conf.bot->hub && !conf.bot->localhub)
  645. fatal(STR("something is wrong."), 0);
  646. if (!(i = crontab_exists())) {
  647. crontab_create(5);
  648. if (!(i = crontab_exists()))
  649. printf(STR("* Error writing crontab entry.\n"));
  650. }
  651. }
  652. static void crontab_install(bd::Stream& crontab) {
  653. // Write out the new crontab
  654. Tempfile new_crontab = Tempfile("crontab");
  655. crontab.writeFile(new_crontab.fd);
  656. // Install new crontab
  657. const char* argv[] = {"crontab", new_crontab.file, 0};
  658. simple_exec(argv);
  659. }
  660. void crontab_del() {
  661. bd::Stream crontab;
  662. if (crontab_exists(&crontab, 1) == 1)
  663. crontab_install(crontab);
  664. }
  665. int crontab_exists(bd::Stream* crontab, bool excludeSelf) {
  666. char *out = NULL;
  667. int ret = -1;
  668. if (shell_exec("crontab -l", NULL, &out, NULL, 1)) {
  669. if (out) {
  670. bd::Stream stream(out);
  671. bd::String line;
  672. ret = 0;
  673. while (stream.tell() < stream.length()) {
  674. line = stream.getline();
  675. if (line[0] != '#' && line.find(binname) != bd::String::npos) {
  676. ret = 1;
  677. // Need to continue if the existing crontab is requested
  678. if (crontab && !excludeSelf)
  679. (*crontab) << line;
  680. else if (!crontab)
  681. break;
  682. } else if (crontab)
  683. (*crontab) << line;
  684. }
  685. free(out);
  686. } else
  687. ret = 0;
  688. }
  689. return ret;
  690. }
  691. char s1_2[3] = "",s1_8[3] = "",s2_5[3] = "";
  692. void crontab_create(int interval) {
  693. bd::Stream crontab;
  694. if (crontab_exists(&crontab) == 1)
  695. return;
  696. char buf[1024] = "";
  697. if (interval == 1)
  698. strlcpy(buf, "*", 2);
  699. else {
  700. int i = 1;
  701. int si = randint(interval);
  702. while (i < 60) {
  703. if (buf[0])
  704. strlcat(buf, ",", sizeof(buf));
  705. simple_snprintf(&buf[strlen(buf)], sizeof(buf) - strlen(buf), "%i", (i + si) % 60);
  706. i += interval;
  707. }
  708. }
  709. simple_snprintf(buf + strlen(buf), sizeof buf, STR(" * * * * %s > /dev/null 2>&1\n"), shell_escape(binname));
  710. crontab << buf;
  711. crontab_install(crontab);
  712. }
  713. int det_translate(const char *word)
  714. {
  715. if (word && word[0]) {
  716. if (!strcasecmp(word, STR("ignore")))
  717. return DET_IGNORE;
  718. else if (!strcasecmp(word, STR("warn")))
  719. return DET_WARN;
  720. else if (!strcasecmp(word, STR("reject")))
  721. return DET_REJECT;
  722. else if (!strcasecmp(word, STR("die")))
  723. return DET_DIE;
  724. else if (!strcasecmp(word, STR("suicide")))
  725. return DET_SUICIDE;
  726. }
  727. return DET_IGNORE;
  728. }
  729. const char *det_translate_num(int num)
  730. {
  731. switch (num) {
  732. case DET_IGNORE: return STR("ignore");
  733. case DET_WARN: return STR("warn");
  734. case DET_REJECT: return STR("reject");
  735. case DET_DIE: return STR("die");
  736. case DET_SUICIDE:return STR("suicide");
  737. default: return STR("ignore");
  738. }
  739. return STR("ignore");
  740. }
  741. char *shell_escape(const char *path)
  742. {
  743. static char ret1[DIRMAX] = "", ret2[DIRMAX] = "", *ret = NULL;
  744. static bool alt = 0;
  745. char *c = NULL;
  746. if (alt) {
  747. alt = 0;
  748. ret = ret1;
  749. } else {
  750. alt = 1;
  751. ret = ret2;
  752. }
  753. ret[0] = 0;
  754. for (c = (char *) path; c && *c; ++c) {
  755. if (strchr(ESCAPESHELL, *c))
  756. simple_snprintf(&ret[strlen(ret)], sizeof(ret1) - strlen(ret), "\\%c", *c);
  757. else
  758. simple_snprintf(&ret[strlen(ret)], sizeof(ret1) - strlen(ret), "%c", *c);
  759. }
  760. return ret;
  761. }