contrib upd from Nelson
[sxemacs] / lib-src / fakemail.c
1 /* sendmail-like interface to /bin/mail for system V,
2    Copyright (C) 1985, 1994 Free Software Foundation, Inc.
3
4 This file is part of SXEmacs.
5
6 SXEmacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 SXEmacs is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program.  If not, see <http://www.gnu.org/licenses/>. */
18
19 /* Synched up with: FSF 19.28. */
20
21 #define NO_SHORTNAMES
22 #include <config.h>
23
24 #if defined (BSD) && !defined (BSD4_1) && !defined (USE_FAKEMAIL)
25 /* This program is not used in BSD, so just avoid loader complaints.  */
26 int main(int argc, char *argv[])
27 {
28         return 0;
29 }
30 #elif defined (LINUX)
31 #include <stdio.h>
32 #include <stdlib.h>
33 int main(int argc, char *argv[])
34 {
35         /* Linux /bin/mail, if it exists, is NOT the Unix v7 mail that
36            fakemail depends on!  This causes garbled mail.  Better to
37            output an error message. */
38         fprintf(stderr, "Sorry, fakemail does not work on Linux.\n");
39         fprintf(stderr, "Make sure you have the sendmail program, and\n");
40         fprintf(stderr, "set the Lisp variable `sendmail-program' to point\n");
41         fprintf(stderr, "to the path of the sendmail binary.\n");
42         return 1;
43 }
44 #else                           /* not BSD 4.2 (or newer) */
45
46 /* These are defined in config in some versions. */
47
48 #ifdef static
49 #undef static
50 #endif
51
52 #ifdef read
53 #undef read
54 #undef write
55 #undef open
56 #undef close
57 #endif
58
59 #include <stdio.h>
60 #if __STDC__ || defined(STDC_HEADERS)
61 #include <stdlib.h>
62 #include <unistd.h>
63 #endif
64 #include <string.h>
65 #include <ctype.h>
66 #include <time.h>
67 #include <pwd.h>
68 \f
69 /* Type definitions */
70
71 #define boolean int
72 #define true 1
73 #define false 0
74
75 /* Various lists */
76
77 struct line_record {
78         char *string;
79         struct line_record *continuation;
80 };
81 typedef struct line_record *line_list;
82
83 struct header_record {
84         line_list text;
85         struct header_record *next;
86         struct header_record *previous;
87 };
88 typedef struct header_record *header;
89
90 struct stream_record {
91         FILE *handle;
92         int (*action) (FILE *);
93         struct stream_record *rest_streams;
94 };
95 typedef struct stream_record *stream_list;
96
97 /* A `struct linebuffer' is a structure which holds a line of text.
98  * `readline' reads a line from a stream into a linebuffer
99  * and works regardless of the length of the line.
100  */
101
102 struct linebuffer {
103         size_t size;
104         char *buffer;
105 };
106
107 struct linebuffer lb;
108
109 #define new_list()                                      \
110   ((line_list) xmalloc (sizeof (struct line_record)))
111 #define new_header()                            \
112   ((header) xmalloc (sizeof (struct header_record)))
113 #define new_stream()                            \
114   ((stream_list) xmalloc (sizeof (struct stream_record)))
115 #define alloc_string(nchars)                            \
116   ((char *) xmalloc ((nchars) + 1))
117 \f
118 /* Global declarations */
119
120 #define BUFLEN 1024
121 #define KEYWORD_SIZE 256
122 #define FROM_PREFIX "From"
123 #define MY_NAME "fakemail"
124 #define NIL ((line_list) NULL)
125 #define INITIAL_LINE_SIZE 200
126
127 #ifndef MAIL_PROGRAM_NAME
128 #define MAIL_PROGRAM_NAME "/bin/mail"
129 #endif
130
131 #define xstrncpy(d_,s_,l_)                      \
132         do {                                    \
133                 char* dst_=d_;                  \
134                 dst_[0]='\0';                   \
135                 strncat((dst_),(s_),(l_)-1);    \
136         } while(0)
137
138 static const char *my_name;
139 static char *the_date;
140 static char *the_user;
141 static line_list file_preface;
142 static stream_list the_streams;
143 static boolean no_problems = true;
144
145 #if !__STDC__ && !defined(STDC_HEADERS)
146 extern FILE *popen();
147 extern int fclose(), pclose();
148 extern char *malloc(), *realloc();
149 #endif
150
151 #if defined(__FreeBSD_version) && __FreeBSD_version >= 400000
152 #define CURRENT_USER
153 #endif
154
155 #ifdef CURRENT_USER
156 extern struct passwd *getpwuid();
157 #if defined(__FreeBSD_version) && __FreeBSD_version >= 400000
158 extern uid_t geteuid ();
159 #else
160 extern unsigned short geteuid();
161 #endif
162 static struct passwd *my_entry;
163 #define cuserid(s)                              \
164 (my_entry = getpwuid ((int) geteuid ()),        \
165  my_entry->pw_name)
166 #endif
167 \f
168 /* Utilities */
169
170 /* Print error message.  `s1' is printf control string, `s2' is arg for it. */
171
172 static void error(const char *s1, const char *s2)
173 {
174         printf("%s: ", my_name);
175         printf(s1, s2);
176         printf("\n");
177         no_problems = false;
178 }
179
180 /* Print error message and exit.  */
181
182 static void fatal(const char *s1, const char *s2)
183 {
184         error(s1, s2);
185         exit(1);
186 }
187
188 /* Like malloc but get fatal error if memory is exhausted.  */
189
190 static void *xmalloc(size_t size)
191 {
192         void *result = malloc(size);
193         if (result == NULL)
194                 fatal("virtual memory exhausted", (char *)0);
195         return result;
196 }
197
198 static void *xrealloc(void *ptr, size_t size)
199 {
200         void *result = realloc(ptr, size);
201         if (result == NULL)
202                 fatal("virtual memory exhausted", (char *)0);
203         return result;
204 }
205 \f
206 /* Initialize a linebuffer for use */
207
208 static void init_linebuffer(struct linebuffer *linebuffer)
209 {
210         linebuffer->size = INITIAL_LINE_SIZE;
211         linebuffer->buffer = (char *)xmalloc(INITIAL_LINE_SIZE);
212 }
213
214 /* Read a line of text from `stream' into `linebuffer'.
215  * Return the length of the line.
216  */
217
218 static long readline(struct linebuffer *linebuffer, FILE * stream)
219 {
220         char *buffer = linebuffer->buffer;
221         char *p = linebuffer->buffer;
222         char *end = p + linebuffer->size;
223
224         while (true) {
225                 int c = getc(stream);
226                 if (p == end) {
227                         linebuffer->size *= 2;
228                         buffer = (char *)xrealloc(buffer, linebuffer->size);
229                         p = buffer + (p - linebuffer->buffer);
230                         end = buffer + linebuffer->size;
231                         linebuffer->buffer = buffer;
232                 }
233                 if (c < 0 || c == '\n') {
234                         *p = 0;
235                         break;
236                 }
237                 *p++ = c;
238         }
239
240         return p - buffer;
241 }
242 \f
243 static char *get_keyword(register char *field, char **rest)
244 {
245         static char keyword[KEYWORD_SIZE];
246         register char *ptr;
247         register char c;
248
249         ptr = &keyword[0];
250         c = *field++;
251         if ((isspace((int)(unsigned char)c)) || (c == ':'))
252                 return (char *)NULL;
253         *ptr++ = ((islower((int)(unsigned char)c)) ?
254                   (toupper((int)(unsigned char)c)) : c);
255         while (((c = *field++) != ':') && (!(isspace((int)(unsigned char)c))))
256                 *ptr++ = ((islower((int)(unsigned char)c)) ?
257                           (toupper((int)(unsigned char)c)) : c);
258         *ptr++ = '\0';
259         while (isspace((int)(unsigned char)c))
260                 c = *field++;
261         if (c != ':')
262                 return (char *)NULL;
263         *rest = field;
264         return &keyword[0];
265 }
266
267 static boolean has_keyword(char *field)
268 {
269         char *ignored;
270         return (get_keyword(field, &ignored) != (char *)NULL);
271 }
272
273 static char *add_field(line_list the_list, register char *field,
274                        register char *where)
275 {
276         register char c;
277         while (true) {
278                 *where++ = ' ';
279                 while ((c = *field++) != '\0') {
280                         if (c == '(') {
281                                 while (*field && *field != ')')
282                                         ++field;
283                                 if (!(*field++))
284                                         break;  /* no closer */
285                                 if (!(*field))
286                                         break;  /* closerNULL */
287                                 c = *field;
288                         }
289                         *where++ =
290                             ((c == ',' || c == '>' || c == '<') ? ' ' : c);
291                 }
292                 if (the_list == NIL)
293                         break;
294                 field = the_list->string;
295                 the_list = the_list->continuation;
296         }
297         return where;
298 }
299 \f
300 static line_list make_file_preface(void)
301 {
302         char *the_string, *temp;
303         time_t idiotic_interface;
304         long prefix_length;
305         long user_length;
306         long date_length;
307         line_list result;
308         size_t the_string_len, the_user_len, temp_len;
309
310         prefix_length = strlen(FROM_PREFIX);
311         time(&idiotic_interface);
312         the_date = ctime(&idiotic_interface);
313         /* the_date has an unwanted newline at the end */
314         date_length = strlen(the_date) - 1;
315         if (the_date[date_length] == '\n')
316                 the_date[date_length] = '\0';
317         temp = cuserid((char *)NULL);
318         /* the_user */
319         the_user_len = strlen(temp);
320         the_user = alloc_string(the_user_len);
321         xstrncpy(the_user, temp, the_user_len+1);
322         /* alloc the_string */
323         the_string_len = 3 + prefix_length + the_user_len + date_length;
324         the_string = alloc_string(the_string_len);
325         temp_len = the_string_len+1;
326         temp = the_string;
327         xstrncpy(temp, FROM_PREFIX, temp_len);
328
329         temp = &temp[prefix_length];
330         *temp++ = ' ';
331         temp_len -= prefix_length + 1;
332         xstrncpy(temp, the_user, temp_len);
333
334         temp = &temp[the_user_len];
335         *temp++ = ' ';
336         temp_len -= the_user_len + 1;
337         xstrncpy(temp, the_date, temp_len);
338
339         result = new_list();
340         result->string = the_string;
341         result->continuation = ((line_list) NULL);
342         return result;
343 }
344
345 static void write_line_list(register line_list the_list, FILE * the_stream)
346 {
347         for (;
348              the_list != ((line_list) NULL);
349              the_list = the_list->continuation) {
350                 fputs(the_list->string, the_stream);
351                 putc('\n', the_stream);
352         }
353         return;
354 }
355 \f
356 static int close_the_streams(void)
357 {
358         register stream_list rem;
359         for (rem = the_streams;
360              rem != ((stream_list) NULL); rem = rem->rest_streams)
361                 no_problems = (no_problems &&
362                                ((*rem->action) (rem->handle) == 0));
363         the_streams = ((stream_list) NULL);
364         return (no_problems ? 0 : 1);
365 }
366
367 static void add_a_stream(FILE * the_stream, int (*closing_action) (FILE *))
368 {
369         stream_list old = the_streams;
370         the_streams = new_stream();
371         the_streams->handle = the_stream;
372         the_streams->action = closing_action;
373         the_streams->rest_streams = old;
374         return;
375 }
376
377 static int my_fclose(FILE * the_file)
378 {
379         putc('\n', the_file);
380         fflush(the_file);
381         return fclose(the_file);
382 }
383
384 static boolean open_a_file(char *name)
385 {
386         FILE *the_stream = fopen(name, "a");
387         if (the_stream != ((FILE *) NULL)) {
388                 add_a_stream(the_stream, my_fclose);
389                 if (the_user == (char *)NULL)
390                         file_preface = make_file_preface();
391                 write_line_list(file_preface, the_stream);
392                 return true;
393         }
394         return false;
395 }
396
397 static void put_string(char *s)
398 {
399         register stream_list rem;
400         for (rem = the_streams;
401              rem != ((stream_list) NULL); rem = rem->rest_streams)
402                 fputs(s, rem->handle);
403         return;
404 }
405
406 static void put_line(const char *string)
407 {
408         register stream_list rem;
409         for (rem = the_streams;
410              rem != ((stream_list) NULL); rem = rem->rest_streams) {
411                 const char *s = string;
412                 int column = 0;
413
414                 /* Divide STRING into lines.  */
415                 while (*s != 0) {
416                         const char *breakpos;
417
418                         /* Find the last char that fits.  */
419                         for (breakpos = s; *breakpos && column < 78; ++breakpos) {
420                                 if (*breakpos == '\t')
421                                         column += 8;
422                                 else
423                                         column++;
424                         }
425                         /* If we didn't reach end of line, break the line.  */
426                         if (*breakpos) {
427                                 /* Back up to just after the last comma that fits.  */
428                                 while (breakpos != s && breakpos[-1] != ',')
429                                         --breakpos;
430
431                                 if (breakpos == s) {
432                                         /* If no comma fits, move past the first address anyway.  */
433                                         while (*breakpos != 0
434                                                && *breakpos != ',')
435                                                 ++breakpos;
436                                         if (*breakpos != 0)
437                                                 /* Include the comma after it.  */
438                                                 ++breakpos;
439                                 }
440                         }
441                         /* Output that much, then break the line.  */
442                         fwrite(s, 1, breakpos - s, rem->handle);
443                         column = 8;
444
445                         /* Skip whitespace and prepare to print more addresses.  */
446                         s = breakpos;
447                         while (*s == ' ' || *s == '\t')
448                                 ++s;
449                         if (*s != 0)
450                                 fputs("\n\t", rem->handle);
451                 }
452                 putc('\n', rem->handle);
453         }
454         return;
455 }
456 \f
457 #define mail_error error
458
459 static void setup_files(register line_list the_list, register char *field)
460 {
461         register char *start;
462         register char c;
463         while (true) {
464                 while (((c = *field) != '\0') &&
465                        ((c == ' ') || (c == '\t') || (c == ',')))
466                         field += 1;
467                 if (c != '\0') {
468                         start = field;
469                         while (((c = *field) != '\0') &&
470                                (c != ' ') && (c != '\t') && (c != ','))
471                                 field += 1;
472                         *field = '\0';
473                         if (!open_a_file(start))
474                                 mail_error("Could not open file %s", start);
475                         *field = c;
476                         if (c != '\0')
477                                 continue;
478                 }
479                 if (the_list == ((line_list) NULL))
480                         return;
481                 field = the_list->string;
482                 the_list = the_list->continuation;
483         }
484 }
485 \f
486 static int args_size(header the_header)
487 {
488         register header old = the_header;
489         register line_list rem;
490         register int size = 0;
491         do {
492                 char *field;
493                 register char *keyword =
494                     get_keyword(the_header->text->string, &field);
495                 if ((strcmp(keyword, "TO") == 0) || (strcmp(keyword, "CC") == 0)
496                     || (strcmp(keyword, "BCC") == 0)) {
497                         size += 1 + strlen(field);
498                         for (rem = the_header->text->continuation;
499                              rem != NIL; rem = rem->continuation)
500                                 size += 1 + strlen(rem->string);
501                 }
502                 the_header = the_header->next;
503         } while (the_header != old);
504         return size;
505 }
506
507 static void parse_header(header the_header, register char *where)
508 {
509         register header old = the_header;
510         do {
511                 char *field;
512                 register char *keyword =
513                     get_keyword(the_header->text->string, &field);
514                 if (strcmp(keyword, "TO") == 0)
515                         where =
516                             add_field(the_header->text->continuation, field,
517                                       where);
518                 else if (strcmp(keyword, "CC") == 0)
519                         where =
520                             add_field(the_header->text->continuation, field,
521                                       where);
522                 else if (strcmp(keyword, "BCC") == 0) {
523                         where =
524                             add_field(the_header->text->continuation, field,
525                                       where);
526                         the_header->previous->next = the_header->next;
527                         the_header->next->previous = the_header->previous;
528                 } else if (strcmp(keyword, "FCC") == 0)
529                         setup_files(the_header->text->continuation, field);
530                 the_header = the_header->next;
531         } while (the_header != old);
532         *where = '\0';
533         return;
534 }
535 \f
536 static header read_header(void)
537 {
538         register header the_header = ((header) NULL);
539         register line_list *next_line = ((line_list *) NULL);
540
541         init_linebuffer(&lb);
542
543         do {
544                 long length;
545                 register char *line;
546
547                 readline(&lb, stdin);
548                 line = lb.buffer;
549                 length = strlen(line);
550                 if (length == 0)
551                         break;
552
553                 if (has_keyword(line)) {
554                         register header old = the_header;
555                         the_header = new_header();
556                         if (old == ((header) NULL)) {
557                                 the_header->next = the_header;
558                                 the_header->previous = the_header;
559                         } else {
560                                 the_header->previous = old;
561                                 the_header->next = old->next;
562                                 old->next = the_header;
563                         }
564                         next_line = &(the_header->text);
565                 }
566
567                 if (next_line == ((line_list *) NULL)) {
568                         /* Not a valid header */
569                         exit(1);
570                 }
571                 *next_line = new_list();
572                 (*next_line)->string = alloc_string((size_t) length);
573                 xstrncpy(((*next_line)->string), length, line);
574                 next_line = &((*next_line)->continuation);
575                 *next_line = NIL;
576
577         } while (true);
578
579         return the_header->next;
580 }
581 \f
582 static void write_header(header the_header)
583 {
584         register header old = the_header;
585         do {
586                 register line_list the_list;
587                 for (the_list = the_header->text;
588                      the_list != NIL; the_list = the_list->continuation)
589                         put_line(the_list->string);
590                 the_header = the_header->next;
591         } while (the_header != old);
592         put_line("");
593         return;
594 }
595 \f
596 int main(int argc, char *argv[])
597 {
598         char *command_line;
599         size_t command_line_len;
600         header the_header;
601         long name_length;
602         char *mail_program_name;
603         char buf[BUFLEN + 1];
604         register int size;
605         FILE *the_pipe;
606
607         mail_program_name = getenv("FAKEMAILER");
608         if (!(mail_program_name && *mail_program_name))
609                 mail_program_name = (char *)MAIL_PROGRAM_NAME;
610         name_length = strlen(mail_program_name);
611
612         my_name = MY_NAME;
613         the_streams = ((stream_list) NULL);
614         the_date = (char *)NULL;
615         the_user = (char *)NULL;
616
617         the_header = read_header();
618         command_line_len = name_length + args_size(the_header);
619         command_line = alloc_string(command_line_len);
620         xstrncpy(command_line, command_line_len, mail_program_name);
621         parse_header(the_header, &command_line[name_length]);
622
623         the_pipe = popen(command_line, "w");
624         if (the_pipe == ((FILE *) NULL))
625                 fatal("cannot open pipe to real mailer", (char *)NULL);
626
627         add_a_stream(the_pipe, pclose);
628
629         write_header(the_header);
630
631         /* Dump the message itself */
632
633         while (!feof(stdin)) {
634                 size = fread(buf, 1, BUFLEN, stdin);
635                 buf[size] = '\0';
636                 put_string(buf);
637         }
638
639         return close_the_streams();
640 }
641
642 #endif                          /* not BSD 4.2 (or newer) */