*: introduce and use xfork() and xvfork()
[oweals/busybox.git] / mailutils / mail.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * helper routines
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 void kill_helper(void)
13 {
14         if (G.helper_pid > 0) {
15                 kill(G.helper_pid, SIGTERM);
16                 G.helper_pid = 0;
17         }
18 }
19
20 // generic signal handler
21 static void signal_handler(int signo)
22 {
23 #define err signo
24         if (SIGALRM == signo) {
25                 kill_helper();
26                 bb_error_msg_and_die("timed out");
27         }
28
29         // SIGCHLD. reap zombies
30         if (safe_waitpid(G.helper_pid, &err, WNOHANG) > 0) {
31                 if (WIFSIGNALED(err))
32                         bb_error_msg_and_die("helper killed by signal %u", WTERMSIG(err));
33                 if (WIFEXITED(err)) {
34                         G.helper_pid = 0;
35                         if (WEXITSTATUS(err))
36                                 bb_error_msg_and_die("helper exited (%u)", WEXITSTATUS(err));
37                 }
38         }
39 #undef err
40 }
41
42 void FAST_FUNC launch_helper(const char **argv)
43 {
44         // setup vanilla unidirectional pipes interchange
45         int i;
46         int pipes[4];
47
48         xpipe(pipes);
49         xpipe(pipes + 2);
50
51         // NB: handler must be installed before vfork
52         bb_signals(0
53                 + (1 << SIGCHLD)
54                 + (1 << SIGALRM)
55                 , signal_handler);
56
57         G.helper_pid = xvfork();
58
59         i = (!G.helper_pid) * 2; // for parent:0, for child:2
60         close(pipes[i + 1]); // 1 or 3 - closing one write end
61         close(pipes[2 - i]); // 2 or 0 - closing one read end
62         xmove_fd(pipes[i], STDIN_FILENO); // 0 or 2 - using other read end
63         xmove_fd(pipes[3 - i], STDOUT_FILENO); // 3 or 1 - other write end
64
65         if (!G.helper_pid) {
66                 // child: try to execute connection helper
67                 // NB: SIGCHLD & SIGALRM revert to SIG_DFL on exec
68                 BB_EXECVP_or_die((char**)argv);
69         }
70
71         // parent
72         // check whether child is alive
73         //redundant:signal_handler(SIGCHLD);
74         // child seems OK -> parent goes on
75         atexit(kill_helper);
76 }
77
78 const FAST_FUNC char *command(const char *fmt, const char *param)
79 {
80         const char *msg = fmt;
81         if (timeout)
82                 alarm(timeout);
83         if (msg) {
84                 msg = xasprintf(fmt, param);
85                 printf("%s\r\n", msg);
86         }
87         fflush_all();
88         return msg;
89 }
90
91 // NB: parse_url can modify url[] (despite const), but only if '@' is there
92 /*
93 static char FAST_FUNC *parse_url(char *url, char **user, char **pass)
94 {
95         // parse [user[:pass]@]host
96         // return host
97         char *s = strchr(url, '@');
98         *user = *pass = NULL;
99         if (s) {
100                 *s++ = '\0';
101                 *user = url;
102                 url = s;
103                 s = strchr(*user, ':');
104                 if (s) {
105                         *s++ = '\0';
106                         *pass = s;
107                 }
108         }
109         return url;
110 }
111 */
112
113 void FAST_FUNC encode_base64(char *fname, const char *text, const char *eol)
114 {
115         enum {
116                 SRC_BUF_SIZE = 45,  /* This *MUST* be a multiple of 3 */
117                 DST_BUF_SIZE = 4 * ((SRC_BUF_SIZE + 2) / 3),
118         };
119
120 #define src_buf text
121         FILE *fp = fp;
122         ssize_t len = len;
123         char dst_buf[DST_BUF_SIZE + 1];
124
125         if (fname) {
126                 fp = (NOT_LONE_DASH(fname)) ? xfopen_for_read(fname) : (FILE *)text;
127                 src_buf = bb_common_bufsiz1;
128         // N.B. strlen(NULL) segfaults!
129         } else if (text) {
130                 // though we do not call uuencode(NULL, NULL) explicitly
131                 // still we do not want to break things suddenly
132                 len = strlen(text);
133         } else
134                 return;
135
136         while (1) {
137                 size_t size;
138                 if (fname) {
139                         size = fread((char *)src_buf, 1, SRC_BUF_SIZE, fp);
140                         if ((ssize_t)size < 0)
141                                 bb_perror_msg_and_die(bb_msg_read_error);
142                 } else {
143                         size = len;
144                         if (len > SRC_BUF_SIZE)
145                                 size = SRC_BUF_SIZE;
146                 }
147                 if (!size)
148                         break;
149                 // encode the buffer we just read in
150                 bb_uuencode(dst_buf, src_buf, size, bb_uuenc_tbl_base64);
151                 if (fname) {
152                         printf("%s\n", eol);
153                 } else {
154                         src_buf += size;
155                         len -= size;
156                 }
157                 fwrite(dst_buf, 1, 4 * ((size + 2) / 3), stdout);
158         }
159         if (fname && NOT_LONE_DASH(fname))
160                 fclose(fp);
161 #undef src_buf
162 }
163
164 void FAST_FUNC decode_base64(FILE *src_stream, FILE *dst_stream)
165 {
166         int term_count = 1;
167
168         while (1) {
169                 char translated[4];
170                 int count = 0;
171
172                 while (count < 4) {
173                         char *table_ptr;
174                         int ch;
175
176                         /* Get next _valid_ character.
177                          * global vector bb_uuenc_tbl_base64[] contains this string:
178                          * "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n"
179                          */
180                         do {
181                                 ch = fgetc(src_stream);
182                                 if (ch == EOF) {
183                                         bb_error_msg_and_die(bb_msg_read_error);
184                                 }
185                                 // - means end of MIME section
186                                 if ('-' == ch) {
187                                         // push it back
188                                         ungetc(ch, src_stream);
189                                         return;
190                                 }
191                                 table_ptr = strchr(bb_uuenc_tbl_base64, ch);
192                         } while (table_ptr == NULL);
193
194                         /* Convert encoded character to decimal */
195                         ch = table_ptr - bb_uuenc_tbl_base64;
196
197                         if (*table_ptr == '=') {
198                                 if (term_count == 0) {
199                                         translated[count] = '\0';
200                                         break;
201                                 }
202                                 term_count++;
203                         } else if (*table_ptr == '\n') {
204                                 /* Check for terminating line */
205                                 if (term_count == 5) {
206                                         return;
207                                 }
208                                 term_count = 1;
209                                 continue;
210                         } else {
211                                 translated[count] = ch;
212                                 count++;
213                                 term_count = 0;
214                         }
215                 }
216
217                 /* Merge 6 bit chars to 8 bit */
218                 if (count > 1) {
219                         fputc(translated[0] << 2 | translated[1] >> 4, dst_stream);
220                 }
221                 if (count > 2) {
222                         fputc(translated[1] << 4 | translated[2] >> 2, dst_stream);
223                 }
224                 if (count > 3) {
225                         fputc(translated[2] << 6 | translated[3], dst_stream);
226                 }
227         }
228 }
229
230
231 /*
232  * get username and password from a file descriptor
233  */
234 void FAST_FUNC get_cred_or_die(int fd)
235 {
236         if (isatty(fd)) {
237                 G.user = xstrdup(bb_ask(fd, /* timeout: */ 0, "User: "));
238                 G.pass = xstrdup(bb_ask(fd, /* timeout: */ 0, "Password: "));
239         } else {
240                 G.user = xmalloc_reads(fd, /* pfx: */ NULL, /* maxsize: */ NULL);
241                 G.pass = xmalloc_reads(fd, /* pfx: */ NULL, /* maxsize: */ NULL);
242         }
243         if (!G.user || !*G.user || !G.pass)
244                 bb_error_msg_and_die("no username or password");
245 }