This repository has been archived by the owner on Sep 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmail_on_failure.c
112 lines (98 loc) · 2.48 KB
/
mail_on_failure.c
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
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>
char* read_systemd_variable(const char *unit, const char *property) {
int filedes[2];
if (pipe(filedes) == -1) {
perror("pipe");
exit(1);
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
} else if (pid == 0) {
while ((dup2(filedes[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {}
close(filedes[1]);
close(filedes[0]);
char *arg;
asprintf(&arg, "--property=%s", property);
execl("/usr/bin/systemctl", "systemctl", "show", unit, arg, NULL);
perror("execl");
_exit(1);
}
close(filedes[1]);
char buffer[4096];
memset(buffer, '\0', sizeof(buffer));
read(filedes[0], buffer, sizeof(buffer));
close(filedes[0]);
wait(0);
char *result;
asprintf(&result, "%s", buffer + strlen(property) + 1);
result[strlen(result)-1] = '\0';
return result;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <unit>\n", argv[0]);
exit(1);
}
struct stat sb;
if (stat("/usr/sbin/sendmail", &sb) == -1) {
fprintf(stderr, "<3>can't send error mail for %s without a MTA\n", argv[1]);
exit(1);
}
char *mailto = NULL;
char *environment;
environment = read_systemd_variable(argv[1], "Environment");
printf("[%s]\n", environment);
if (strlen(environment)) {
// leak
mailto = strstr(environment, "MAILTO=");
if (mailto) {
mailto += strlen("MAILTO=");
char *p;
p = strchr(mailto, ' ');
if (p)
p[0] = '\0';
if (!strlen(mailto)) {
free(environment);
exit(0);
}
}
}
if (!mailto) {
mailto = read_systemd_variable(argv[1], "User");
if(!strlen(mailto)) {
free(mailto);
mailto = strdup("root");
}
}
printf("Mailto: [%s]\n", mailto);
/*
hostname = os.uname()[1]
body = "From: root (systemd-cron)\n"
body += "To: " + mailto + "\n"
body += "Subject: [" + hostname + "] job " + job + " failed\n"
body += "MIME-Version: 1.0\n"
body += "Content-Type: text/plain; charset=UTF-8\n"
body += "Content-Transfer-Encoding: 8bit\n"
body += "Auto-Submitted: auto-generated\n"
body += "\n"
try:
systemctl = subprocess.check_output(['systemctl','status',job], universal_newlines=True)
except subprocess.CalledProcessError as e:
if e.returncode != 3:
raise
else:
body += e.output
p = Popen(['sendmail','-i','-B8BITMIME',mailto], stdin=PIPE)
p.communicate(bytes(body, 'UTF-8'))
*/
free(environment);
}