sendmail: fixes by Vladimir Dronnikov <dronnikov at gmail.com>
[oweals/busybox.git] / networking / sendmail.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * bare bones sendmail
4  *
5  * Copyright (C) 2008 by Vladimir Dronnikov <dronnikov@gmail.com>
6  *
7  * Licensed under GPLv2, see file LICENSE in this tarball for details.
8  */
9 #include "libbb.h"
10
11 /*
12    Extracted from BB uuencode.c
13  */
14 enum {
15         SRC_BUF_SIZE = 45,  /* This *MUST* be a multiple of 3 */
16         DST_BUF_SIZE = 4 * ((SRC_BUF_SIZE + 2) / 3),
17 };
18
19 static void uuencode(char *fname, const char *text)
20 {
21 #define src_buf text
22         int fd;
23 #define len fd
24         char dst_buf[DST_BUF_SIZE + 1];
25
26         if (fname) {
27                 fd = xopen(fname, O_RDONLY);
28                 src_buf = bb_common_bufsiz1;
29         } else {
30                 len = strlen(text);
31         }
32
33         fflush(stdout); // sync stdio and unistd output
34         while (1) {
35                 size_t size;
36                 if (fname) {
37                         size = full_read(fd, (char *)src_buf, SRC_BUF_SIZE);
38                         if ((ssize_t)size < 0)
39                                 bb_perror_msg_and_die(bb_msg_read_error);
40                 } else {
41                         size = len;
42                         if (len > SRC_BUF_SIZE)
43                                 size = SRC_BUF_SIZE;
44                 }
45                 if (!size)
46                         break;
47                 // Encode the buffer we just read in
48                 bb_uuencode(dst_buf, src_buf, size, bb_uuenc_tbl_base64);
49                 if (fname) {
50                         xwrite(STDOUT_FILENO, "\n", 1);
51                 } else {
52                         src_buf += size;
53                         len -= size;
54                 }
55                 xwrite(STDOUT_FILENO, dst_buf, 4 * ((size + 2) / 3));
56         }
57         if (ENABLE_FEATURE_CLEAN_UP && fname)
58                 close(fd);
59 }
60
61 #if ENABLE_FEATURE_SENDMAIL_NETWORK
62 // generic signal handler
63 static void signal_handler(int signo)
64 {
65         int err;
66
67         if (SIGALRM == signo)
68                 bb_error_msg_and_die("timed out");
69
70         // SIGCHLD. reap zombies
71         if (wait_any_nohang(&err) > 0)
72                 if (WIFEXITED(err) && WEXITSTATUS(err))
73                         bb_error_msg_and_die("child exited (%d)", WEXITSTATUS(err));
74 }
75
76 static pid_t helper_pid;
77
78 // read stdin, parses first bytes to a number, i.e. server response
79 // if code = -1 then just return this number
80 // if code != -1 then checks whether the number equals the code
81 // if not equal -> die saying errmsg
82 static int check(int code, const char *errmsg)
83 {
84         char *answer;
85
86         // read a string and match it against the set of available answers
87         fflush(stdout);
88         answer = xmalloc_getline(stdin);
89         if (answer) {
90                 int n = atoi(answer);
91                 if (-1 == code || n == code) {
92                         free(answer);
93                         return n;
94                 }
95         }
96         // TODO: is there more elegant way to terminate child on program failure?
97         if (helper_pid > 0)
98                 kill(helper_pid, SIGTERM);
99         if (!answer)
100                 answer = (char*)"EOF";
101         else
102                 *strchrnul(answer, '\r') = '\0';
103         bb_error_msg_and_die("error at %s: got '%s' instead", errmsg, answer);
104 }
105
106 static int puts_and_check(const char *msg, int code, const char *errmsg)
107 {
108         printf("%s\r\n", msg);
109         return check(code, errmsg);
110 }
111
112 // strip argument of bad chars
113 static char *sane(char *str)
114 {
115         char *s = str;
116         char *p = s;
117         while (*s) {
118                 if (isalnum(*s) || '_' == *s || '-' == *s || '.' == *s || '@' == *s) {
119                         *p++ = *s;
120                 }
121                 s++;
122         }
123         *p = '\0';
124         return str;
125 }
126 #endif
127
128 int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
129 int sendmail_main(int argc, char **argv)
130 {
131         llist_t *recipients = NULL;
132         llist_t *bodies = NULL;
133         llist_t *attachments = NULL;
134         char *from;
135         char *notify = NULL;
136         const char *subject;
137         char *charset = (char*)"utf-8";
138 #if ENABLE_FEATURE_SENDMAIL_NETWORK
139         const char *wsecs = "10";
140         const char *server = "127.0.0.1";
141         const char *port = NULL;
142         const char *opt_user;
143         const char *opt_pass;
144         unsigned timeout;
145 #endif
146         char *boundary;
147         unsigned opts;
148         enum {
149                 OPT_f = 1 << 0,         // sender
150                 OPT_n = 1 << 2,         // notification
151                 OPT_s = 1 << 3,         // subject given
152                 OPT_c = 1 << 6,         // charset
153                 OPT_d = 1 << 7,         // dry run - no networking
154                 OPT_w = 1 << 8,         // network timeout
155                 OPT_h = 1 << 9,         // server
156                 OPT_p = 1 << 10,        // port
157                 OPT_U = 1 << 11,        // user specified
158                 OPT_P = 1 << 12,        // password specified
159         };
160
161         // -f must be specified
162         // -t, -b, -a may be multiple
163         opt_complementary = "f:t::b::a::";
164         opts = getopt32(argv,
165                 "f:t:n::s:b:a:c:" USE_FEATURE_SENDMAIL_NETWORK("dw:h:p:U:P:"),
166                 &from, &recipients, &notify, &subject, &bodies, &attachments, &charset
167                 USE_FEATURE_SENDMAIL_NETWORK(, &wsecs, &server, &port, &opt_user, &opt_pass)
168         );
169         //argc -= optind;
170         argv += optind;
171
172         // sanitize user input
173         sane(from);
174         if (opts & OPT_c)
175                 sane(charset);
176
177         // establish connection
178 #if ENABLE_FEATURE_SENDMAIL_NETWORK
179         timeout = xatou(wsecs);
180         if (!(opts & OPT_d)) {
181                 // ask password if we need to and while we're still have terminal
182                 // TODO: get password directly from /dev/tty? or from a secret file?
183                 if ((opts & (OPT_U+OPT_P)) == OPT_U) {
184                         if (!isatty(STDIN_FILENO) || !(opt_pass = bb_askpass(0, "Password: "))) {
185                                 bb_error_msg_and_die("no password");
186                         }
187                 }
188                 // set chat timeout
189                 alarm(timeout);
190                 // connect to server
191                 if (argv[0]) {
192                         // if connection helper given
193                         // setup vanilla unidirectional pipes interchange
194                         int idx;
195                         int pipes[4];
196                         xpipe(pipes);
197                         xpipe(pipes+2);
198                         helper_pid = vfork();
199                         if (helper_pid < 0)
200                                 bb_perror_msg_and_die("vfork");
201                         idx = (!helper_pid)*2;
202                         xdup2(pipes[idx], STDIN_FILENO);
203                         xdup2(pipes[3-idx], STDOUT_FILENO);
204                         if (ENABLE_FEATURE_CLEAN_UP)
205                                 for (int i = 4; --i >= 0;)
206                                         if (pipes[i] > STDOUT_FILENO)
207                                                 close(pipes[i]);
208                         // replace child with connection helper
209                         if (!helper_pid) {
210                                 // child - try to execute connection helper
211                                 BB_EXECVP(argv[0], argv);
212                                 _exit(127);
213                         }
214                         // parent - check whether child is alive
215                         sig_catch(SIGCHLD, signal_handler);
216                         sig_catch(SIGALRM, signal_handler);
217                         signal_handler(SIGCHLD);
218                         // child seems OK -> parent goes on SMTP chat
219                 } else {
220                         // no connection helper provided -> make plain connect
221                         int fd = create_and_connect_stream_or_die(
222                                 server,
223                                 bb_lookup_port(port, "tcp", 25)
224                         );
225                         xmove_fd(fd, STDIN_FILENO);
226                         xdup2(STDIN_FILENO, STDOUT_FILENO);
227                         // wait for OK
228                         check(220, "INIT");
229                 }
230                 // mail user specified? try modern AUTHentication
231                 if ((opts & OPT_U)
232                  && (334 == puts_and_check("auth login", -1, "auth login"))
233                 ) {
234                         uuencode(NULL, opt_user);
235                         puts_and_check("", 334, "AUTH");
236                         uuencode(NULL, opt_pass);
237                         puts_and_check("", 235, "AUTH");
238                 // no mail user specified or modern AUTHentication is not supported?
239                 } else {
240                         // fallback to simple HELO authentication
241                         // fetch domain name (defaults to local)
242                         const char *domain = strchr(from, '@');
243                         if (domain)
244                                 domain++;
245                         else
246                                 domain = "local";
247                         printf("helo %s\r\n", domain);
248                         check(250, "HELO");
249                 }
250
251                 // set addresses
252                 printf("mail from:<%s>\r\n", from);
253                 check(250, "MAIL FROM");
254                 for (llist_t *to = recipients; to; to = to->link) {
255                         printf("rcpt to:<%s>\r\n", sane(to->data));
256                         check(250, "RCPT TO");
257                 }
258                 puts_and_check("data", 354, "DATA");
259                 // no timeout while sending message
260                 alarm(0);
261         }
262 #endif
263
264         // now put message
265         // put address headers
266         printf("From: %s\r\n", from);
267         for (llist_t *to = recipients; to; to = to->link) {
268                 printf("To: %s\r\n", sane(to->data));
269         }
270         // put encoded subject
271         if (opts & OPT_s) {
272                 printf("Subject: =?%s?B?", charset);
273                 uuencode(NULL, subject);
274                 puts("?=\r");
275         }
276         // put notification
277         if (opts & OPT_n) {
278                 // -n without parameter?
279                 if (!notify)
280                         notify = from; // notify sender by default
281                 printf("Disposition-Notification-To: %s\r\n", sane(notify));
282         }
283         // put common headers and body start
284         //srand(?);
285         boundary = xasprintf("%d-%d-%d", rand(), rand(), rand());
286         printf(
287                 "X-Mailer: busybox " BB_VER " sendmail\r\n"
288                 "Message-ID: <%s>\r\n"
289                 "Mime-Version: 1.0\r\n"
290                 "%smultipart/mixed; boundary=\"%s\"\r\n"
291                 "\r\n"
292                 "--%s\r\n"
293                 "%stext/plain; charset=%s\r\n"
294                 "%s\r\n%s"
295                 , boundary
296                 , "Content-Type: "
297                 , boundary, boundary
298                 , "Content-Type: "
299                 , charset
300                 , "Content-Disposition: inline"
301                 , "Content-Transfer-Encoding: base64\r\n"
302         );
303         // put body(ies)
304         for (llist_t *f = bodies; f; f = f->link) {
305                 uuencode(f->data, NULL);
306         }
307         // put attachment(s)
308         for (llist_t *f = attachments; f; f = f->link) {
309                 printf(
310                         "\r\n--%s\r\n"
311                         "%sapplication/octet-stream\r\n"
312                         "%s; filename=\"%s\"\r\n"
313                         "%s"
314                         , boundary
315                         , "Content-Type: "
316                         , "Content-Disposition: inline"
317                         , bb_get_last_path_component_strip(f->data)
318                         , "Content-Transfer-Encoding: base64\r\n"
319                 );
320                 uuencode(f->data, NULL);
321         }
322         // put terminator
323         printf("\r\n--%s--\r\n\r\n", boundary);
324         if (ENABLE_FEATURE_CLEAN_UP)
325                 free(boundary);
326
327 #if ENABLE_FEATURE_SENDMAIL_NETWORK
328         // end message and say goodbye
329         if (!(opts & OPT_d)) {
330                 alarm(timeout);
331                 puts_and_check(".", 250, "BODY");
332                 puts_and_check("quit", 221, "QUIT");
333         }
334 #endif
335
336         return 0;
337 }