summaryrefslogtreecommitdiffstats
path: root/email.c
blob: 31c22b8ebe409ea260d394655b5ab2b9e0dba00f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <syslog.h>
#include <fcntl.h>
#include <unistd.h>

#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);
}