014b20dc8df25841826b9e28c669aca9b85ac620
[oweals/busybox.git] / mailutils / 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 #include "mail.h"
11
12 static int smtp_checkp(const char *fmt, const char *param, int code)
13 {
14         char *answer;
15         const char *msg = command(fmt, param);
16         // read stdin
17         // if the string has a form \d\d\d- -- read next string. E.g. EHLO response
18         // parse first bytes to a number
19         // if code = -1 then just return this number
20         // if code != -1 then checks whether the number equals the code
21         // if not equal -> die saying msg
22         while ((answer = xmalloc_fgetline(stdin)) != NULL)
23                 if (strlen(answer) <= 3 || '-' != answer[3])
24                         break;
25         if (answer) {
26                 int n = atoi(answer);
27                 if (timeout)
28                         alarm(0);
29                 free(answer);
30                 if (-1 == code || n == code)
31                         return n;
32         }
33         bb_error_msg_and_die("%s failed", msg);
34 }
35
36 static int smtp_check(const char *fmt, int code)
37 {
38         return smtp_checkp(fmt, NULL, code);
39 }
40
41 // strip argument of bad chars
42 static char *sane_address(char *str)
43 {
44         char *s = str;
45         char *p = s;
46         while (*s) {
47                 if (isalnum(*s) || '_' == *s || '-' == *s || '.' == *s || '@' == *s) {
48                         *p++ = *s;
49                 }
50                 s++;
51         }
52         *p = '\0';
53         return str;
54 }
55
56 static void rcptto(const char *s)
57 {
58         smtp_checkp("RCPT TO:<%s>", s, 250);
59 }
60
61 int sendmail_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
62 int sendmail_main(int argc UNUSED_PARAM, char **argv)
63 {
64         char *opt_connect = opt_connect;
65         char *opt_from;
66         char *s;
67         llist_t *list = NULL;
68         char *domain = sane_address(safe_getdomainname());
69         int code;
70
71         enum {
72         //--- standard options
73                 OPT_t = 1 << 0,         // read message for recipients, append them to those on cmdline
74                 OPT_f = 1 << 1,         // sender address
75                 OPT_o = 1 << 2,         // various options. -oi IMPLIED! others are IGNORED!
76                 OPT_i = 1 << 3,         // IMPLIED!
77         //--- BB specific options
78                 OPT_w = 1 << 4,         // network timeout
79                 OPT_H = 1 << 5,         // use external connection helper
80                 OPT_S = 1 << 6,         // specify connection string
81                 OPT_a = 1 << 7,         // authentication tokens
82         };
83
84         // init global variables
85         INIT_G();
86
87         // save initial stdin since body is piped!
88         xdup2(STDIN_FILENO, 3);
89         G.fp0 = fdopen(3, "r");
90
91         // parse options
92         // -f is required. -H and -S are mutually exclusive
93         opt_complementary = "f:w+:H--S:S--H:a::";
94         // N.B. since -H and -S are mutually exclusive they do not interfere in opt_connect
95         // -a is for ssmtp (http://downloads.openwrt.org/people/nico/man/man8/ssmtp.8.html) compatibility,
96         // it is still under development.
97         opts = getopt32(argv, "tf:o:iw:H:S:a::", &opt_from, NULL, &timeout, &opt_connect, &opt_connect, &list);
98         //argc -= optind;
99         argv += optind;
100
101         // process -a[upm]<token> options
102         if ((opts & OPT_a) && !list)
103                 bb_show_usage();
104         while (list) {
105                 char *a = (char *) llist_pop(&list);
106                 if ('u' == a[0])
107                         G.user = xstrdup(a+1);
108                 if ('p' == a[0])
109                         G.pass = xstrdup(a+1);
110                 // N.B. we support only AUTH LOGIN so far
111                 //if ('m' == a[0])
112                 //      G.method = xstrdup(a+1);
113         }
114         // N.B. list == NULL here
115         //bb_info_msg("OPT[%x] AU[%s], AP[%s], AM[%s], ARGV[%s]", opts, au, ap, am, *argv);
116
117         // connect to server
118
119         // connection helper ordered? ->
120         if (opts & OPT_H) {
121                 const char *args[] = { "sh", "-c", opt_connect, NULL };
122                 // plug it in
123                 launch_helper(args);
124         // vanilla connection
125         } else {
126                 int fd;
127                 // host[:port] not explicitly specified? -> use $SMTPHOST
128                 // no $SMTPHOST ? -> use localhost
129                 if (!(opts & OPT_S)) {
130                         opt_connect = getenv("SMTPHOST");
131                         if (!opt_connect)
132                                 opt_connect = (char *)"127.0.0.1";
133                 }
134                 // do connect
135                 fd = create_and_connect_stream_or_die(opt_connect, 25);
136                 // and make ourselves a simple IO filter
137                 xmove_fd(fd, STDIN_FILENO);
138                 xdup2(STDIN_FILENO, STDOUT_FILENO);
139         }
140         // N.B. from now we know nothing about network :)
141
142         // wait for initial server OK
143         // N.B. if we used openssl the initial 220 answer is already swallowed during openssl TLS init procedure
144         // so we need to kick the server to see whether we are ok
145         code = smtp_check("NOOP", -1);
146         // 220 on plain connection, 250 on openssl-helped TLS session
147         if (220 == code)
148                 smtp_check(NULL, 250); // reread the code to stay in sync
149         else if (250 != code)
150                 bb_error_msg_and_die("INIT failed");
151
152         // we should start with modern EHLO
153         if (250 != smtp_checkp("EHLO %s", domain, -1)) {
154                 smtp_checkp("HELO %s", domain, 250);
155         }
156         if (ENABLE_FEATURE_CLEAN_UP)
157                 free(domain);
158
159         // perform authentication
160         if (opts & OPT_a) {
161                 smtp_check("AUTH LOGIN", 334);
162                 // we must read credentials unless they are given via -a[up] options
163                 if (!G.user || !G.pass)
164                         get_cred_or_die(4);
165                 encode_base64(NULL, G.user, NULL);
166                 smtp_check("", 334);
167                 encode_base64(NULL, G.pass, NULL);
168                 smtp_check("", 235);
169         }
170
171         // set sender
172         // N.B. we have here a very loosely defined algotythm
173         // since sendmail historically offers no means to specify secrets on cmdline.
174         // 1) server can require no authentication ->
175         //      we must just provide a (possibly fake) reply address.
176         // 2) server can require AUTH ->
177         //      we must provide valid username and password along with a (possibly fake) reply address.
178         //      For the sake of security username and password are to be read either from console or from a secured file.
179         //      Since reading from console may defeat usability, the solution is either to read from a predefined
180         //      file descriptor (e.g. 4), or again from a secured file.
181
182         // got no sender address? -> use system username as a resort
183         // N.B. we marked -f as required option!
184         //if (!G.user) {
185         //      // N.B. IMHO getenv("USER") can be way easily spoofed!
186         //      G.user = xuid2uname(getuid());
187         //      opt_from = xasprintf("%s@%s", G.user, domain);
188         //}
189         //if (ENABLE_FEATURE_CLEAN_UP)
190         //      free(domain);
191         smtp_checkp("MAIL FROM:<%s>", opt_from, 250);
192
193         // process message
194
195         // read recipients from message and add them to those given on cmdline.
196         // this means we scan stdin for To:, Cc:, Bcc: lines until an empty line
197         // and then use the rest of stdin as message body
198         code = 0; // set "analyze headers" mode
199         while ((s = xmalloc_fgetline(G.fp0)) != NULL) {
200                 // put message lines doubling leading dots
201                 if (code) {
202                         // escape leading dots
203                         // N.B. this feature is implied even if no -i (-oi) switch given
204                         // N.B. we need to escape the leading dot regardless of
205                         // whether it is single or not character on the line
206                         if ('.' == s[0] /*&& '\0' == s[1] */)
207                                 printf(".");
208                         // dump read line
209                         printf("%s\r\n", s);
210                         free(s);
211                         continue;
212                 }
213
214                 // analyze headers
215                 // To: or Cc: headers add recipients
216                 if (0 == strncasecmp("To: ", s, 4) || 0 == strncasecmp("Bcc: " + 1, s, 4)) {
217                         rcptto(sane_address(s+4));
218 //                      goto addh;
219                         llist_add_to_end(&list, s);
220                 // Bcc: header adds blind copy (hidden) recipient
221                 } else if (0 == strncasecmp("Bcc: ", s, 5)) {
222                         rcptto(sane_address(s+5));
223                         free(s);
224                         // N.B. Bcc: vanishes from headers!
225                 // other headers go verbatim
226                 } else if (s[0]) {
227 // addh:
228                         llist_add_to_end(&list, s);
229                 // the empty line stops analyzing headers
230                 } else {
231                         free(s);
232                         // put recipients specified on cmdline
233                         while (*argv) {
234                                 s = sane_address(*argv);
235                                 rcptto(s);
236                                 llist_add_to_end(&list, xasprintf("To: %s", s));
237                                 argv++;
238                         }
239                         // enter "put message" mode
240                         smtp_check("DATA", 354);
241                         // dump the headers
242                         while (list) {
243                                 printf("%s\r\n", (char *) llist_pop(&list));
244                         }
245                         printf("%s\r\n" + 2); // quirk for format string to be reused
246                         // stop analyzing headers
247                         code++;
248                 }
249         }
250
251         // finalize the message
252         smtp_check(".", 250);
253         // ... and say goodbye
254         smtp_check("QUIT", 221);
255         // cleanup
256         if (ENABLE_FEATURE_CLEAN_UP)
257                 fclose(G.fp0);
258
259         return EXIT_SUCCESS;
260 }