* patch #3966: Create a mh_xmalloc function to prevent mistakes when
[mmh] / uip / mhstore.c
1
2 /*
3  * mhstore.c -- 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 #include <h/utils.h>
24
25 #ifdef HAVE_SYS_WAIT_H
26 # include <sys/wait.h>
27 #endif
28
29 /*
30  * We allocate space for message names (msgs array)
31  * this number of elements at a time.
32  */
33 #define MAXMSGS  256
34
35
36 static struct swit switches[] = {
37 #define AUTOSW                  0
38     { "auto", 0 },
39 #define NAUTOSW                 1
40     { "noauto", 0 },
41 #define CHECKSW                 2
42     { "check", 0 },
43 #define NCHECKSW                3
44     { "nocheck", 0 },
45 #define VERBSW                  4
46     { "verbose", 0 },
47 #define NVERBSW                 5
48     { "noverbose", 0 },
49 #define FILESW                  6       /* interface from show */
50     { "file file", 0 },
51 #define PARTSW                  7
52     { "part number", 0 },
53 #define TYPESW                  8
54     { "type content", 0 },
55 #define RCACHESW                9
56     { "rcache policy", 0 },
57 #define WCACHESW               10
58     { "wcache policy", 0 },
59 #define VERSIONSW              11
60     { "version", 0 },
61 #define HELPSW                 12
62     { "help", 0 },
63
64 /*
65  * switches for debugging
66  */
67 #define DEBUGSW                13
68     { "debug", -5 },
69     { NULL, 0 }
70 };
71
72
73 /* mhparse.c */
74 extern int checksw;
75 extern char *tmp;       /* directory to place temp files */
76
77 /* mhcachesbr.c */
78 extern int rcachesw;
79 extern int wcachesw;
80 extern char *cache_public;
81 extern char *cache_private;
82
83 /* mhstoresbr.c */
84 extern int autosw;
85 extern char *cwd;       /* cache current working directory */
86
87 /* mhmisc.c */
88 extern int npart;
89 extern int ntype;
90 extern char *parts[NPARTS + 1];
91 extern char *types[NTYPES + 1];
92 extern int userrs;
93
94 int debugsw = 0;
95 int verbosw = 0;
96
97 /* The list of top-level contents to display */
98 CT *cts = NULL;
99
100 #define quitser pipeser
101
102 /* mhparse.c */
103 CT parse_mime (char *);
104
105 /* mhmisc.c */
106 int part_ok (CT, int);
107 int type_ok (CT, int);
108 void set_endian (void);
109 void flush_errors (void);
110
111 /* mhstoresbr.c */
112 void store_all_messages (CT *);
113
114 /* mhfree.c */
115 void free_content (CT);
116
117 /*
118  * static prototypes
119  */
120 static RETSIGTYPE pipeser (int);
121
122
123 int
124 main (int argc, char **argv)
125 {
126     int nummsgs, maxmsgs, msgnum, *icachesw;
127     char *cp, *file = NULL, *folder = NULL;
128     char *maildir, buf[100], **argp;
129     char **arguments, **msgs;
130     struct msgs *mp = NULL;
131     CT ct, *ctp;
132     FILE *fp;
133
134 #ifdef LOCALE
135     setlocale(LC_ALL, "");
136 #endif
137     invo_name = r1bindex (argv[0], '/');
138
139     /* read user profile/context */
140     context_read();
141
142     arguments = getarguments (invo_name, argc, argv, 1);
143     argp = arguments;
144
145     /*
146      * Allocate the initial space to record message
147      * names, ranges, and sequences.
148      */
149     nummsgs = 0;
150     maxmsgs = MAXMSGS;
151     msgs = (char **) mh_xmalloc ((size_t) (maxmsgs * sizeof(*msgs)));
152
153     /*
154      * Parse arguments
155      */
156     while ((cp = *argp++)) {
157         if (*cp == '-') {
158             switch (smatch (++cp, switches)) {
159             case AMBIGSW: 
160                 ambigsw (cp, switches);
161                 done (1);
162             case UNKWNSW: 
163                 adios (NULL, "-%s unknown", cp);
164
165             case HELPSW: 
166                 snprintf (buf, sizeof(buf), "%s [+folder] [msgs] [switches]",
167                         invo_name);
168                 print_help (buf, switches, 1);
169                 done (1);
170             case VERSIONSW:
171                 print_version(invo_name);
172                 done (1);
173
174             case AUTOSW:
175                 autosw++;
176                 continue;
177             case NAUTOSW:
178                 autosw = 0;
179                 continue;
180
181             case RCACHESW:
182                 icachesw = &rcachesw;
183                 goto do_cache;
184             case WCACHESW:
185                 icachesw = &wcachesw;
186 do_cache:
187                 if (!(cp = *argp++) || *cp == '-')
188                     adios (NULL, "missing argument to %s", argp[-2]);
189                 switch (*icachesw = smatch (cp, caches)) {
190                 case AMBIGSW:
191                     ambigsw (cp, caches);
192                     done (1);
193                 case UNKWNSW:
194                     adios (NULL, "%s unknown", cp);
195                 default:
196                     break;
197                 }
198                 continue;
199
200             case CHECKSW:
201                 checksw++;
202                 continue;
203             case NCHECKSW:
204                 checksw = 0;
205                 continue;
206
207             case PARTSW:
208                 if (!(cp = *argp++) || *cp == '-')
209                     adios (NULL, "missing argument to %s", argp[-2]);
210                 if (npart >= NPARTS)
211                     adios (NULL, "too many parts (starting with %s), %d max",
212                            cp, NPARTS);
213                 parts[npart++] = cp;
214                 continue;
215
216             case TYPESW:
217                 if (!(cp = *argp++) || *cp == '-')
218                     adios (NULL, "missing argument to %s", argp[-2]);
219                 if (ntype >= NTYPES)
220                     adios (NULL, "too many types (starting with %s), %d max",
221                            cp, NTYPES);
222                 types[ntype++] = cp;
223                 continue;
224
225             case FILESW:
226                 if (!(cp = *argp++) || (*cp == '-' && cp[1]))
227                     adios (NULL, "missing argument to %s", argp[-2]);
228                 file = *cp == '-' ? cp : path (cp, TFILE);
229                 continue;
230
231             case VERBSW: 
232                 verbosw = 1;
233                 continue;
234             case NVERBSW: 
235                 verbosw = 0;
236                 continue;
237             case DEBUGSW:
238                 debugsw = 1;
239                 continue;
240             }
241         }
242         if (*cp == '+' || *cp == '@') {
243             if (folder)
244                 adios (NULL, "only one folder at a time!");
245             else
246                 folder = path (cp + 1, *cp == '+' ? TFOLDER : TSUBCWF);
247         } else {
248             /*
249              * Check if we need to allocate more space
250              * for message names/ranges/sequences.
251              */
252             if (nummsgs >= maxmsgs) {
253                 maxmsgs += MAXMSGS;
254                 if (!(msgs = (char **) realloc (msgs,
255                         (size_t) (maxmsgs * sizeof(*msgs)))))
256                     adios (NULL, "unable to reallocate msgs storage");
257             }
258             msgs[nummsgs++] = cp;
259         }
260     }
261
262     /* null terminate the list of acceptable parts/types */
263     parts[npart] = NULL;
264     types[ntype] = NULL;
265
266     set_endian ();
267
268     /*
269      * Check if we've specified an additional profile
270      */
271     if ((cp = getenv ("MHSTORE"))) {
272         if ((fp = fopen (cp, "r"))) {
273             readconfig ((struct node **) 0, fp, cp, 0);
274             fclose (fp);
275         } else {
276             admonish ("", "unable to read $MHSTORE profile (%s)", cp);
277         }
278     }
279
280     /*
281      * Read the standard profile setup
282      */
283     if ((fp = fopen (cp = etcpath ("mhn.defaults"), "r"))) {
284         readconfig ((struct node **) 0, fp, cp, 0);
285         fclose (fp);
286     }
287
288     /* Check for public cache location */
289     if ((cache_public = context_find (nmhcache)) && *cache_public != '/')
290         cache_public = NULL;
291
292     /* Check for private cache location */
293     if (!(cache_private = context_find (nmhprivcache)))
294         cache_private = ".cache";
295     cache_private = getcpy (m_maildir (cache_private));
296
297     /*
298      * Cache the current directory before we do any chdirs()'s.
299      */
300     cwd = getcpy (pwd());
301
302     /*
303      * Check for storage directory.  If specified,
304      * then store temporary files there.  Else we
305      * store them in standard nmh directory.
306      */
307     if ((cp = context_find (nmhstorage)) && *cp)
308         tmp = concat (cp, "/", invo_name, NULL);
309     else
310         tmp = add (m_maildir (invo_name), NULL);
311
312     if (!context_find ("path"))
313         free (path ("./", TFOLDER));
314
315     if (file && nummsgs)
316         adios (NULL, "cannot specify msg and file at same time!");
317
318     /*
319      * check if message is coming from file
320      */
321     if (file) {
322         if (!(cts = (CT *) calloc ((size_t) 2, sizeof(*cts))))
323             adios (NULL, "out of memory");
324         ctp = cts;
325
326         if ((ct = parse_mime (file)));
327             *ctp++ = ct;
328     } else {
329         /*
330          * message(s) are coming from a folder
331          */
332         if (!nummsgs)
333             msgs[nummsgs++] = "cur";
334         if (!folder)
335             folder = getfolder (1);
336         maildir = m_maildir (folder);
337
338         if (chdir (maildir) == NOTOK)
339             adios (maildir, "unable to change directory to");
340
341         /* read folder and create message structure */
342         if (!(mp = folder_read (folder)))
343             adios (NULL, "unable to read folder %s", folder);
344
345         /* check for empty folder */
346         if (mp->nummsg == 0)
347             adios (NULL, "no messages in %s", folder);
348
349         /* parse all the message ranges/sequences and set SELECTED */
350         for (msgnum = 0; msgnum < nummsgs; msgnum++)
351             if (!m_convert (mp, msgs[msgnum]))
352                 done (1);
353         seq_setprev (mp);       /* set the previous-sequence */
354
355         if (!(cts = (CT *) calloc ((size_t) (mp->numsel + 1), sizeof(*cts))))
356             adios (NULL, "out of memory");
357         ctp = cts;
358
359         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
360             if (is_selected(mp, msgnum)) {
361                 char *msgnam;
362
363                 msgnam = m_name (msgnum);
364                 if ((ct = parse_mime (msgnam)))
365                     *ctp++ = ct;
366             }
367         }
368     }
369
370     if (!*cts)
371         done (1);
372
373     userrs = 1;
374     SIGNAL (SIGQUIT, quitser);
375     SIGNAL (SIGPIPE, pipeser);
376
377     /*
378      * Get the associated umask for the relevant contents.
379      */
380     for (ctp = cts; *ctp; ctp++) {
381         struct stat st;
382
383         ct = *ctp;
384         if (type_ok (ct, 1) && !ct->c_umask) {
385             if (stat (ct->c_file, &st) != NOTOK)
386                 ct->c_umask = ~(st.st_mode & 0777);
387             else
388                 ct->c_umask = ~m_gmprot();
389         }
390     }
391
392     /*
393      * Store the message content
394      */
395     store_all_messages (cts);
396
397     /* Now free all the structures for the content */
398     for (ctp = cts; *ctp; ctp++)
399         free_content (*ctp);
400
401     free ((char *) cts);
402     cts = NULL;
403
404     /* If reading from a folder, do some updating */
405     if (mp) {
406         context_replace (pfolder, folder);/* update current folder  */
407         seq_setcur (mp, mp->hghsel);      /* update current message */
408         seq_save (mp);                    /* synchronize sequences  */
409         context_save ();                  /* save the context file  */
410     }
411
412     return done (0);
413 }
414
415
416 static RETSIGTYPE
417 pipeser (int i)
418 {
419     if (i == SIGQUIT) {
420         unlink ("core");
421         fflush (stdout);
422         fprintf (stderr, "\n");
423         fflush (stderr);
424     }
425
426     done (1);
427     /* NOTREACHED */
428 }
429
430
431 int
432 done (int status)
433 {
434     CT *ctp;
435
436     if ((ctp = cts))
437         for (; *ctp; ctp++)
438             free_content (*ctp);
439
440     exit (status);
441     return 1;  /* dead code to satisfy the compiler */
442 }