* patch #3966: Create a mh_xmalloc function to prevent mistakes when
[mmh] / uip / mhn.c
1
2 /*
3  * mhn.c -- display, list, cache, or store the contents of MIME messages
4  *
5  * $Id$
6  *
7  * This code is Copyright (c) 2002, by the authors of nmh.  See the
8  * COPYRIGHT file in the root directory of the nmh distribution for
9  * complete copyright information.
10  */
11
12 #include <h/mh.h>
13 #include <fcntl.h>
14 #include <h/signals.h>
15 #include <h/md5.h>
16 #include <errno.h>
17 #include <signal.h>
18 #include <h/mts.h>
19 #include <h/tws.h>
20 #include <h/mime.h>
21 #include <h/mhparse.h>
22 #include <h/mhcachesbr.h>
23
24 #ifdef HAVE_SYS_WAIT_H
25 # include <sys/wait.h>
26 #endif
27
28 /*
29  * We allocate space for message names (msgs array)
30  * this number of elements at a time.
31  */
32 #define MAXMSGS  256
33
34
35 static struct swit switches[] = {
36 #define AUTOSW                  0
37     { "auto", 0 },
38 #define NAUTOSW                 1
39     { "noauto", 0 },
40 #define CACHESW                 2
41     { "cache", 0 },
42 #define NCACHESW                3
43     { "nocache", 0 },
44 #define CHECKSW                 4
45     { "check", 0 },
46 #define NCHECKSW                5
47     { "nocheck", 0 },
48 #define HEADSW                  6
49     { "headers", 0 },
50 #define NHEADSW                 7
51     { "noheaders", 0 },
52 #define LISTSW                  8
53     { "list", 0 },
54 #define NLISTSW                 9
55     { "nolist", 0 },
56 #define PAUSESW                10
57     { "pause", 0 },
58 #define NPAUSESW               11
59     { "nopause", 0 },
60 #define SIZESW                 12
61     { "realsize", 0 },
62 #define NSIZESW                13
63     { "norealsize", 0 },
64 #define SERIALSW               14
65     { "serialonly", 0 },
66 #define NSERIALSW              15
67     { "noserialonly", 0 },
68 #define SHOWSW                 16
69     { "show", 0 },
70 #define NSHOWSW                17
71     { "noshow", 0 },
72 #define STORESW                18
73     { "store", 0 },
74 #define NSTORESW               19
75     { "nostore", 0 },
76 #define VERBSW                 20
77     { "verbose", 0 },
78 #define NVERBSW                21
79     { "noverbose", 0 },
80 #define FILESW                 22       /* interface from show */
81     { "file file", 0 },
82 #define FORMSW                 23
83     { "form formfile", 0 },
84 #define PARTSW                 24
85     { "part number", 0 },
86 #define TYPESW                 25
87     { "type content", 0 },
88 #define RCACHESW               26
89     { "rcache policy", 0 },
90 #define WCACHESW               27
91     { "wcache policy", 0 },
92 #define VERSIONSW              28
93     { "version", 0 },
94 #define HELPSW                 29
95     { "help", 0 },
96
97 /*
98  * switches for debugging
99  */
100 #define DEBUGSW                30
101     { "debug", -5 },
102
103 /*
104  * switches for moreproc/mhlproc
105  */
106 #define PROGSW                 31
107     { "moreproc program", -4 },
108 #define NPROGSW                32
109     { "nomoreproc", -3 },
110 #define LENSW                  33
111     { "length lines", -4 },
112 #define WIDTHSW                34
113     { "width columns", -4 },
114
115 /*
116  * switches for mhbuild
117  */
118 #define BUILDSW                35
119     { "build", -5 },
120 #define NBUILDSW               36
121     { "nobuild", -7 },
122 #define EBCDICSW               37
123     { "ebcdicsafe", -10 },
124 #define NEBCDICSW              38
125     { "noebcdicsafe", -12 },
126 #define RFC934SW               39
127     { "rfc934mode", -10 },
128 #define NRFC934SW              40
129     { "norfc934mode", -12 },
130     { NULL, 0 }
131 };
132
133
134 /* mhparse.c */
135 extern int checksw;
136 extern char *tmp;       /* directory to place temp files */
137
138 /* mhcachesbr.c */
139 extern int rcachesw;
140 extern int wcachesw;
141 extern char *cache_public;
142 extern char *cache_private;
143
144 /* mhshowsbr.c */
145 extern int pausesw;
146 extern int serialsw;
147 extern char *progsw;
148 extern int nolist;
149 extern int nomore;      /* flags for moreproc/header display */
150 extern char *formsw;
151
152 /* mhstoresbr.c */
153 extern int autosw;
154 extern char *cwd;       /* cache current working directory */
155
156 /* mhmisc.c */
157 extern int npart;
158 extern int ntype;
159 extern char *parts[NPARTS + 1];
160 extern char *types[NTYPES + 1];
161 extern int userrs;
162
163 int debugsw = 0;
164 int verbosw = 0;
165
166 /* The list of top-level contents to display */
167 CT *cts = NULL;
168
169 /*
170  * variables for mhbuild (mhn -build)
171  */
172 static int buildsw  = 0;
173 static int ebcdicsw = 0;
174 static int rfc934sw = 0;
175
176 /*
177  * what action to take?
178  */
179 static int cachesw = 0;
180 static int listsw  = 0;
181 static int showsw  = 0;
182 static int storesw = 0;
183
184 #define quitser pipeser
185
186 /* mhparse.c */
187 CT parse_mime (char *);
188
189 /* mhmisc.c */
190 int part_ok (CT, int);
191 int type_ok (CT, int);
192 void set_endian (void);
193 void flush_errors (void);
194
195 /* mhshowsbr.c */
196 void show_all_messages (CT *);
197
198 /* mhlistsbr.c */
199 void list_all_messages (CT *, int, int, int, int);
200
201 /* mhstoresbr.c */
202 void store_all_messages (CT *);
203
204 /* mhcachesbr.c */
205 void cache_all_messages (CT *);
206
207 /* mhfree.c */
208 void free_content (CT);
209
210 /*
211  * static prototypes
212  */
213 static RETSIGTYPE pipeser (int);
214
215
216 int
217 main (int argc, char **argv)
218 {
219     int sizesw = 1, headsw = 1;
220     int nummsgs, maxmsgs, msgnum, *icachesw;
221     char *cp, *file = NULL, *folder = NULL;
222     char *maildir, buf[100], **argp;
223     char **arguments, **msgs;
224     struct msgs *mp = NULL;
225     CT ct, *ctp;
226     FILE *fp;
227
228 #ifdef LOCALE
229     setlocale(LC_ALL, "");
230 #endif
231     invo_name = r1bindex (argv[0], '/');
232
233     /* read user profile/context */
234     context_read();
235
236     arguments = getarguments (invo_name, argc, argv, 1);
237     argp = arguments;
238
239     /*
240      * Allocate the initial space to record message
241      * names, ranges, and sequences.
242      */
243     nummsgs = 0;
244     maxmsgs = MAXMSGS;
245     msgs = (char **) mh_xmalloc ((size_t) (maxmsgs * sizeof(*msgs)));
246
247     /*
248      * Parse arguments
249      */
250     while ((cp = *argp++)) {
251         if (*cp == '-') {
252             switch (smatch (++cp, switches)) {
253             case AMBIGSW: 
254                 ambigsw (cp, switches);
255                 done (1);
256             case UNKWNSW: 
257                 adios (NULL, "-%s unknown", cp);
258
259             case HELPSW: 
260                 snprintf (buf, sizeof(buf), "%s [+folder] [msgs] [switches]",
261                         invo_name);
262                 print_help (buf, switches, 1);
263                 done (1);
264             case VERSIONSW:
265                 print_version(invo_name);
266                 done (1);
267
268             case AUTOSW:
269                 autosw++;
270                 continue;
271             case NAUTOSW:
272                 autosw = 0;
273                 continue;
274
275             case CACHESW:
276                 cachesw++;
277                 continue;
278             case NCACHESW:
279                 cachesw = 0;
280                 continue;
281
282             case RCACHESW:
283                 icachesw = &rcachesw;
284                 goto do_cache;
285             case WCACHESW:
286                 icachesw = &wcachesw;
287 do_cache:
288                 if (!(cp = *argp++) || *cp == '-')
289                     adios (NULL, "missing argument to %s", argp[-2]);
290                 switch (*icachesw = smatch (cp, caches)) {
291                 case AMBIGSW:
292                     ambigsw (cp, caches);
293                     done (1);
294                 case UNKWNSW:
295                     adios (NULL, "%s unknown", cp);
296                 default:
297                     break;
298                 }
299                 continue;
300
301             case CHECKSW:
302                 checksw++;
303                 continue;
304             case NCHECKSW:
305                 checksw = 0;
306                 continue;
307
308             case HEADSW:
309                 headsw = 1;
310                 continue;
311             case NHEADSW:
312                 headsw = 0;
313                 continue;
314
315             case LISTSW:
316                 listsw = 1;
317                 continue;
318             case NLISTSW:
319                 listsw = 0;
320                 continue;
321
322             case PAUSESW:
323                 pausesw = 1;
324                 continue;
325             case NPAUSESW:
326                 pausesw = 0;
327                 continue;
328
329             case SERIALSW:
330                 serialsw = 1;
331                 continue;
332             case NSERIALSW:
333                 serialsw = 0;
334                 continue;
335
336             case SHOWSW:
337                 showsw = 1;
338                 continue;
339             case NSHOWSW:
340                 showsw = 0;
341                 continue;
342
343             case SIZESW:
344                 sizesw = 1;
345                 continue;
346             case NSIZESW:
347                 sizesw = 0;
348                 continue;
349
350             case STORESW:
351                 storesw = 1;
352                 continue;
353             case NSTORESW:
354                 storesw = 0;
355                 continue;
356
357             case PARTSW:
358                 if (!(cp = *argp++) || *cp == '-')
359                     adios (NULL, "missing argument to %s", argp[-2]);
360                 if (npart >= NPARTS)
361                     adios (NULL, "too many parts (starting with %s), %d max",
362                            cp, NPARTS);
363                 parts[npart++] = cp;
364                 continue;
365
366             case TYPESW:
367                 if (!(cp = *argp++) || *cp == '-')
368                     adios (NULL, "missing argument to %s", argp[-2]);
369                 if (ntype >= NTYPES)
370                     adios (NULL, "too many types (starting with %s), %d max",
371                            cp, NTYPES);
372                 types[ntype++] = cp;
373                 continue;
374
375             case FILESW:
376                 if (!(cp = *argp++) || (*cp == '-' && cp[1]))
377                     adios (NULL, "missing argument to %s", argp[-2]);
378                 file = *cp == '-' ? cp : path (cp, TFILE);
379                 continue;
380
381             case FORMSW:
382                 if (!(cp = *argp++) || *cp == '-')
383                     adios (NULL, "missing argument to %s", argp[-2]);
384                 if (formsw)
385                     free (formsw);
386                 formsw = getcpy (etcpath (cp));
387                 continue;
388
389             /*
390              * Switches for moreproc/mhlproc
391              */
392             case PROGSW:
393                 if (!(progsw = *argp++) || *progsw == '-')
394                     adios (NULL, "missing argument to %s", argp[-2]);
395                 continue;
396             case NPROGSW:
397                 nomore++;
398                 continue;
399
400             case LENSW:
401             case WIDTHSW:
402                 if (!(cp = *argp++) || *cp == '-')
403                     adios (NULL, "missing argument to %s", argp[-2]);
404                 continue;
405
406             /*
407              * Switches for mhbuild
408              */
409             case BUILDSW:
410                 buildsw = 1;
411                 continue;
412             case NBUILDSW:
413                 buildsw = 0;
414                 continue;
415             case RFC934SW:
416                 rfc934sw = 1;
417                 continue;
418             case NRFC934SW:
419                 rfc934sw = -1;
420                 continue;
421             case EBCDICSW:
422                 ebcdicsw = 1;
423                 continue;
424             case NEBCDICSW:
425                 ebcdicsw = -1;
426                 continue;
427
428             case VERBSW: 
429                 verbosw = 1;
430                 continue;
431             case NVERBSW: 
432                 verbosw = 0;
433                 continue;
434             case DEBUGSW:
435                 debugsw = 1;
436                 continue;
437             }
438         }
439         if (*cp == '+' || *cp == '@') {
440             if (folder)
441                 adios (NULL, "only one folder at a time!");
442             else
443                 folder = path (cp + 1, *cp == '+' ? TFOLDER : TSUBCWF);
444         } else {
445             /*
446              * Check if we need to allocate more space
447              * for message names/ranges/sequences.
448              */
449             if (nummsgs >= maxmsgs) {
450                 maxmsgs += MAXMSGS;
451                 if (!(msgs = (char **) realloc (msgs,
452                         (size_t) (maxmsgs * sizeof(*msgs)))))
453                     adios (NULL, "unable to reallocate msgs storage");
454             }
455             msgs[nummsgs++] = cp;
456         }
457     }
458
459     /* null terminate the list of acceptable parts/types */
460     parts[npart] = NULL;
461     types[ntype] = NULL;
462
463     set_endian ();
464
465     if ((cp = getenv ("MM_NOASK")) && !strcmp (cp, "1")) {
466         nolist  = 1;
467         listsw  = 0;
468         pausesw = 0;
469     }
470
471     /*
472      * Check if we've specified an additional profile
473      */
474     if ((cp = getenv ("MHN"))) {
475         if ((fp = fopen (cp, "r"))) {
476             readconfig ((struct node **) 0, fp, cp, 0);
477             fclose (fp);
478         } else {
479             admonish ("", "unable to read $MHN profile (%s)", cp);
480         }
481     }
482
483     /*
484      * Read the standard profile setup
485      */
486     if ((fp = fopen (cp = etcpath ("mhn.defaults"), "r"))) {
487         readconfig ((struct node **) 0, fp, cp, 0);
488         fclose (fp);
489     }
490
491     /* Check for public cache location */
492     if ((cache_public = context_find (nmhcache)) && *cache_public != '/')
493         cache_public = NULL;
494
495     /* Check for private cache location */
496     if (!(cache_private = context_find (nmhprivcache)))
497         cache_private = ".cache";
498     cache_private = getcpy (m_maildir (cache_private));
499
500     /*
501      * Cache the current directory before we do any chdirs()'s.
502      */
503     cwd = getcpy (pwd());
504
505     /*
506      * Check for storage directory.  If specified,
507      * then store temporary files there.  Else we
508      * store them in standard nmh directory.
509      */
510     if ((cp = context_find (nmhstorage)) && *cp)
511         tmp = concat (cp, "/", invo_name, NULL);
512     else
513         tmp = add (m_maildir (invo_name), NULL);
514
515     if (!context_find ("path"))
516         free (path ("./", TFOLDER));
517
518     /*
519      * Process a mhn composition file (mhn -build)
520      */
521     if (buildsw) {
522         char *vec[MAXARGS];
523         int vecp;
524
525         if (showsw || storesw || cachesw)
526             adios (NULL, "cannot use -build with -show, -store, -cache");
527         if (nummsgs < 1)
528             adios (NULL, "need to specify a %s composition file", invo_name);
529         if (nummsgs > 1)
530             adios (NULL, "only one %s composition file at a time", invo_name);
531
532         vecp = 0;
533         vec[vecp++] = "mhbuild";
534
535         if (ebcdicsw == 1)
536             vec[vecp++] = "-ebcdicsafe";
537         else if (ebcdicsw == -1)
538             vec[vecp++] = "-noebcdicsafe";
539
540         if (rfc934sw == 1)
541             vec[vecp++] = "-rfc934mode";
542         else if (rfc934sw == -1)
543             vec[vecp++] = "-norfc934mode";
544
545         vec[vecp++] = msgs[0];
546         vec[vecp] = NULL;
547
548         execvp ("mhbuild", vec);
549         fprintf (stderr, "unable to exec ");
550         _exit (-1);
551     }
552
553     /*
554      * Process a mhn composition file (old MH style)
555      */
556     if (nummsgs == 1 && !folder && !npart && !cachesw
557         && !showsw && !storesw && !ntype && !file
558         && (cp = getenv ("mhdraft"))
559         && strcmp (cp, msgs[0]) == 0) {
560
561         char *vec[MAXARGS];
562         int vecp;
563
564         vecp = 0;
565         vec[vecp++] = "mhbuild";
566
567         if (ebcdicsw == 1)
568             vec[vecp++] = "-ebcdicsafe";
569         else if (ebcdicsw == -1)
570             vec[vecp++] = "-noebcdicsafe";
571
572         if (rfc934sw == 1)
573             vec[vecp++] = "-rfc934mode";
574         else if (rfc934sw == -1)
575             vec[vecp++] = "-norfc934mode";
576
577         vec[vecp++] = cp;
578         vec[vecp] = NULL;
579
580         execvp ("mhbuild", vec);
581         fprintf (stderr, "unable to exec ");
582         _exit (-1);
583     }
584
585     if (file && nummsgs)
586         adios (NULL, "cannot specify msg and file at same time!");
587
588     /*
589      * check if message is coming from file
590      */
591     if (file) {
592         if (!(cts = (CT *) calloc ((size_t) 2, sizeof(*cts))))
593             adios (NULL, "out of memory");
594         ctp = cts;
595
596         if ((ct = parse_mime (file)));
597             *ctp++ = ct;
598     } else {
599         /*
600          * message(s) are coming from a folder
601          */
602         if (!nummsgs)
603             msgs[nummsgs++] = "cur";
604         if (!folder)
605             folder = getfolder (1);
606         maildir = m_maildir (folder);
607
608         if (chdir (maildir) == NOTOK)
609             adios (maildir, "unable to change directory to");
610
611         /* read folder and create message structure */
612         if (!(mp = folder_read (folder)))
613             adios (NULL, "unable to read folder %s", folder);
614
615         /* check for empty folder */
616         if (mp->nummsg == 0)
617             adios (NULL, "no messages in %s", folder);
618
619         /* parse all the message ranges/sequences and set SELECTED */
620         for (msgnum = 0; msgnum < nummsgs; msgnum++)
621             if (!m_convert (mp, msgs[msgnum]))
622                 done (1);
623         seq_setprev (mp);       /* set the previous-sequence */
624
625         if (!(cts = (CT *) calloc ((size_t) (mp->numsel + 1), sizeof(*cts))))
626             adios (NULL, "out of memory");
627         ctp = cts;
628
629         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
630             if (is_selected(mp, msgnum)) {
631                 char *msgnam;
632
633                 msgnam = m_name (msgnum);
634                 if ((ct = parse_mime (msgnam)))
635                     *ctp++ = ct;
636             }
637         }
638     }
639
640     if (!*cts)
641         done (1);
642
643     /*
644      * You can't give more than one of these flags
645      * at a time.
646      */
647     if (showsw + listsw + storesw + cachesw > 1)
648         adios (NULL, "can only use one of -show, -list, -store, -cache at same time");
649
650     /* If no action is specified, assume -show */
651     if (!listsw && !showsw && !storesw && !cachesw)
652         showsw = 1;
653
654     userrs = 1;
655     SIGNAL (SIGQUIT, quitser);
656     SIGNAL (SIGPIPE, pipeser);
657
658     /*
659      * Get the associated umask for the relevant contents.
660      */
661     for (ctp = cts; *ctp; ctp++) {
662         struct stat st;
663
664         ct = *ctp;
665         if (type_ok (ct, 1) && !ct->c_umask) {
666             if (stat (ct->c_file, &st) != NOTOK)
667                 ct->c_umask = ~(st.st_mode & 0777);
668             else
669                 ct->c_umask = ~m_gmprot();
670         }
671     }
672
673     /*
674      * List the message content
675      */
676     if (listsw)
677         list_all_messages (cts, headsw, sizesw, verbosw, debugsw);
678
679     /*
680      * Store the message content
681      */
682     if (storesw)
683         store_all_messages (cts);
684
685     /*
686      * Cache the message content
687      */
688     if (cachesw)
689         cache_all_messages (cts);
690
691     /*
692      * Show the message content
693      */
694     if (showsw)
695         show_all_messages (cts);
696
697     /* Now free all the structures for the content */
698     for (ctp = cts; *ctp; ctp++)
699         free_content (*ctp);
700
701     free ((char *) cts);
702     cts = NULL;
703
704     /* If reading from a folder, do some updating */
705     if (mp) {
706         context_replace (pfolder, folder);/* update current folder  */
707         seq_setcur (mp, mp->hghsel);      /* update current message */
708         seq_save (mp);                    /* synchronize sequences  */
709         context_save ();                  /* save the context file  */
710     }
711
712     return done (0);
713 }
714
715
716 static RETSIGTYPE
717 pipeser (int i)
718 {
719     if (i == SIGQUIT) {
720         unlink ("core");
721         fflush (stdout);
722         fprintf (stderr, "\n");
723         fflush (stderr);
724     }
725
726     done (1);
727     /* NOTREACHED */
728 }
729
730
731 int
732 done (int status)
733 {
734     CT *ctp;
735
736     if ((ctp = cts))
737         for (; *ctp; ctp++)
738             free_content (*ctp);
739
740     exit (status);
741     return 1;  /* dead code to satisfy the compiler */
742 }