1
0

shell.c 20 KB

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