From bfac22dc79164bab10185188e12cee313ab96de9 Mon Sep 17 00:00:00 2001 From: James <31272717+gpd-pocket-hacker@users.noreply.github.com> Date: Mon, 9 Nov 2020 16:10:37 +0000 Subject: add email support --- email.c | 112 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 112 insertions(+) create mode 100644 email.c (limited to 'email.c') diff --git a/email.c b/email.c new file mode 100644 index 0000000..31c22b8 --- /dev/null +++ b/email.c @@ -0,0 +1,112 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "email.h" + + + +static int daemonish (int nochdir, int noclose) +{ + if (!nochdir && chdir ("/")) + return -1; + + if (!noclose) { + int fd, failed = 0; + + if ((fd = open ("/dev/null", O_RDWR)) < 0) return -1; + + if (dup2 (fd, 0) < 0 || dup2 (fd, 1) < 0 || dup2 (fd, 2) < 0) + failed++; + + if (fd > 2) close (fd); + + if (failed) return -1; + } + + switch (fork()) { + case 0: + break; + + case -1: + return -1; + + default: + return 1;; + } + + if (setsid() < 0) return -1; + + switch (fork()) { + case 0: + break; + + case -1: + return -1; + + default: + _exit (0); + } + + return 0; +} + + +static void write_complete (int fd, const void *_buf, size_t len) +{ + ssize_t writ; + const char *buf = _buf; + + while (len) { + writ = write (fd, buf, len); + + if (writ <= 0) return; + + len -= writ; + buf += writ; + } +} + + +static void write_str (int fd, const char *str) +{ + write_complete (fd, str, strlen (str)); +} + +void send_email (const char *to, const char *subject, const char *body) +{ + int pipes[2]; + + if (daemonish (0, 1)) return; + + pipe (pipes); + + + switch (fork()) { + case 0: + close (pipes[1]); + dup2 (pipes[0], 0); + close (pipes[0]); + + execl ("/usr/lib/sendmail", "sendmail", to, (char *) 0); + _exit (1); + + case -1: + _exit (1); + } + + close (pipes[0]); + + write_str (pipes[1], "Subject: "); + write_str (pipes[1], subject); + write_str (pipes[1], "\n\n"); + write_str (pipes[1], body); + write_str (pipes[1], "\n\n"); + close (pipes[1]); + + _exit (0); +} -- cgit v1.2.3