]> diplodocus.org Git - nmh/blob - uip/sortm.c
lock_file.c: close(2) file descriptor on failure, avoiding leak.
[nmh] / uip / sortm.c
1 /* sortm.c -- sort messages in a folder by date/time
2 *
3 * This code is Copyright (c) 2002, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include <h/mh.h>
9 #include <h/tws.h>
10 #include <h/utils.h>
11 #include "sbr/m_maildir.h"
12
13 #define SORTM_SWITCHES \
14 X("datefield field", 0, DATESW) \
15 X("textfield field", 0, TEXTSW) \
16 X("notextfield", 0, NSUBJSW) \
17 X("subject", -3, SUBJSW) /* backward-compatibility */ \
18 X("limit days", 0, LIMSW) \
19 X("nolimit", 0, NLIMSW) \
20 X("verbose", 0, VERBSW) \
21 X("noverbose", 0, NVERBSW) \
22 X("all", 0, ALLMSGS) \
23 X("noall", 0, NALLMSGS) \
24 X("check", 0, CHECKSW) \
25 X("nocheck", 0, NCHECKSW) \
26 X("version", 0, VERSIONSW) \
27 X("help", 0, HELPSW) \
28
29 #define X(sw, minchars, id) id,
30 DEFINE_SWITCH_ENUM(SORTM);
31 #undef X
32
33 #define X(sw, minchars, id) { sw, minchars, id },
34 DEFINE_SWITCH_ARRAY(SORTM, switches);
35 #undef X
36
37 struct smsg {
38 int s_msg;
39 time_t s_clock;
40 char *s_subj;
41 };
42
43 static struct smsg *smsgs;
44 int nmsgs;
45
46 char *subjsort; /* sort on subject if != 0 */
47 time_t datelimit = 0;
48 int submajor = 0; /* if true, sort on subject-major */
49 int verbose;
50 int allmsgs = 1;
51 int check_failed = 0;
52
53 /* This keeps compiler happy on calls to qsort */
54 typedef int (*qsort_comp) (const void *, const void *);
55
56 /*
57 * static prototypes
58 */
59 static int read_hdrs (struct msgs *, char *);
60 static int get_fields (char *, int, struct smsg *);
61 static int dsort (struct smsg **, struct smsg **);
62 static int subsort (struct smsg **, struct smsg **);
63 static int txtsort (struct smsg **, struct smsg **);
64 static void rename_chain (struct msgs *, struct smsg **, int, int);
65 static void rename_msgs (struct msgs *, struct smsg **);
66
67
68 int
69 main (int argc, char **argv)
70 {
71 int i, msgnum;
72 char *cp, *maildir, *datesw = NULL;
73 char *folder = NULL, buf[BUFSIZ], **argp;
74 char **arguments;
75 struct msgs_array msgs = { 0, 0, NULL };
76 struct msgs *mp;
77 struct smsg **dlist;
78 int checksw = 0;
79
80 if (nmh_init(argv[0], 1)) { return 1; }
81
82 arguments = getarguments (invo_name, argc, argv, 1);
83 argp = arguments;
84
85 /*
86 * Parse arguments
87 */
88 while ((cp = *argp++)) {
89 if (*cp == '-') {
90 switch (smatch (++cp, switches)) {
91 case AMBIGSW:
92 ambigsw (cp, switches);
93 done (1);
94 case UNKWNSW:
95 adios (NULL, "-%s unknown", cp);
96
97 case HELPSW:
98 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]",
99 invo_name);
100 print_help (buf, switches, 1);
101 done (0);
102 case VERSIONSW:
103 print_version(invo_name);
104 done (0);
105
106 case DATESW:
107 if (datesw)
108 adios (NULL, "only one date field at a time");
109 if (!(datesw = *argp++) || *datesw == '-')
110 adios (NULL, "missing argument to %s", argp[-2]);
111 continue;
112
113 case TEXTSW:
114 if (subjsort)
115 adios (NULL, "only one text field at a time");
116 if (!(subjsort = *argp++) || *subjsort == '-')
117 adios (NULL, "missing argument to %s", argp[-2]);
118 continue;
119
120 case SUBJSW:
121 subjsort = "subject";
122 continue;
123 case NSUBJSW:
124 subjsort = NULL;
125 continue;
126
127 case LIMSW:
128 if (!(cp = *argp++) || *cp == '-')
129 adios (NULL, "missing argument to %s", argp[-2]);
130 while (*cp == '0')
131 cp++; /* skip any leading zeros */
132 if (!*cp) { /* hit end of string */
133 submajor++; /* sort subject-major */
134 continue;
135 }
136 if (!isdigit((unsigned char) *cp) || !(datelimit = atoi(cp)))
137 adios (NULL, "impossible limit %s", cp);
138 datelimit *= 60*60*24;
139 continue;
140 case NLIMSW:
141 submajor = 0; /* use date-major, but */
142 datelimit = 0; /* use no limit */
143 continue;
144
145 case VERBSW:
146 verbose++;
147 continue;
148 case NVERBSW:
149 verbose = 0;
150 continue;
151
152 case ALLMSGS:
153 allmsgs = 1;
154 continue;
155 case NALLMSGS:
156 allmsgs = 0;
157 continue;
158
159 case CHECKSW:
160 checksw = 1;
161 continue;
162 case NCHECKSW:
163 checksw = 0;
164 continue;
165 }
166 }
167 if (*cp == '+' || *cp == '@') {
168 if (folder)
169 adios (NULL, "only one folder at a time!");
170 folder = pluspath (cp);
171 } else
172 app_msgarg(&msgs, cp);
173 }
174
175 if (!context_find ("path"))
176 free (path ("./", TFOLDER));
177 if (!msgs.size) {
178 if (allmsgs) {
179 app_msgarg(&msgs, "all");
180 } else {
181 adios (NULL, "must specify messages to sort with -noall");
182 }
183 }
184 if (!datesw)
185 datesw = "date";
186 if (!folder)
187 folder = getfolder (1);
188 maildir = m_maildir (folder);
189
190 if (chdir (maildir) == NOTOK)
191 adios (maildir, "unable to change directory to");
192
193 /* read folder and create message structure */
194 if (!(mp = folder_read (folder, 1)))
195 adios (NULL, "unable to read folder %s", folder);
196
197 /* check for empty folder */
198 if (mp->nummsg == 0)
199 adios (NULL, "no messages in %s", folder);
200
201 /* parse all the message ranges/sequences and set SELECTED */
202 for (msgnum = 0; msgnum < msgs.size; msgnum++)
203 if (!m_convert (mp, msgs.msgs[msgnum]))
204 done (1);
205 seq_setprev (mp); /* set the previous sequence */
206
207 if ((nmsgs = read_hdrs (mp, datesw)) <= 0)
208 adios (NULL, "no messages to sort");
209
210 if (checksw && check_failed) {
211 adios (NULL, "errors found, no messages sorted");
212 }
213
214 /*
215 * sort a list of pointers to our "messages to be sorted".
216 */
217 dlist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*dlist));
218 for (i = 0; i < nmsgs; i++)
219 dlist[i] = &smsgs[i];
220 dlist[nmsgs] = 0;
221
222 if (verbose) { /* announce what we're doing */
223 if (subjsort)
224 if (submajor)
225 printf ("sorting by %s\n", subjsort);
226 else
227 printf ("sorting by %s-major %s-minor\n", subjsort, datesw);
228 else
229 printf ("sorting by datefield %s\n", datesw);
230 }
231
232 /* first sort by date, or by subject-major, date-minor */
233 qsort ((char *) dlist, nmsgs, sizeof(*dlist),
234 (qsort_comp) (submajor && subjsort ? txtsort : dsort));
235
236 /*
237 * if we're sorting on subject, we need another list
238 * in subject order, then a merge pass to collate the
239 * two sorts.
240 */
241 if (!submajor && subjsort) { /* already date sorted */
242 struct smsg **slist, **flist;
243 struct smsg ***il, **fp, **dp;
244
245 slist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*slist));
246 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
247 qsort((char *)slist, nmsgs, sizeof(*slist), (qsort_comp) subsort);
248
249 /*
250 * make an inversion list so we can quickly find
251 * the collection of messages with the same subj
252 * given a message number.
253 */
254 il = mh_xcalloc(mp->hghsel + 1, sizeof *il);
255 for (i = 0; i < nmsgs; i++)
256 il[slist[i]->s_msg] = &slist[i];
257 /*
258 * make up the final list, chronological but with
259 * all the same subjects grouped together.
260 */
261 flist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*flist));
262 fp = flist;
263 for (dp = dlist; *dp;) {
264 struct smsg **s = il[(*dp++)->s_msg];
265
266 /* see if we already did this guy */
267 if (! s)
268 continue;
269
270 *fp++ = *s++;
271 /*
272 * take the next message(s) if there is one,
273 * its subject isn't null and its subject
274 * is the same as this one and it's not too
275 * far away in time.
276 */
277 while (*s && (*s)->s_subj[0] &&
278 strcmp((*s)->s_subj, s[-1]->s_subj) == 0 &&
279 (datelimit == 0 ||
280 (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
281 il[(*s)->s_msg] = 0;
282 *fp++ = *s++;
283 }
284 }
285 *fp = 0;
286 free (il);
287 free (slist);
288 free (dlist);
289 dlist = flist;
290 }
291
292 /*
293 * At this point, dlist is a sorted array of pointers to smsg structures,
294 * each of which contains a message number.
295 */
296
297 rename_msgs (mp, dlist);
298
299 context_replace (pfolder, folder); /* update current folder */
300 seq_save (mp); /* synchronize message sequences */
301 context_save (); /* save the context file */
302 folder_free (mp); /* free folder/message structure */
303 done (0);
304 return 1;
305 }
306
307 static int
308 read_hdrs (struct msgs *mp, char *datesw)
309 {
310 int msgnum;
311 struct smsg *s;
312
313 smsgs = mh_xcalloc(mp->hghsel - mp->lowsel + 2, sizeof *smsgs);
314 s = smsgs;
315 for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
316 if (is_selected(mp, msgnum)) {
317 if (get_fields (datesw, msgnum, s)) {
318 s->s_msg = msgnum;
319 s++;
320 }
321 }
322 }
323 s->s_msg = 0;
324 return(s - smsgs);
325 }
326
327
328 /*
329 * Parse the message and get the data or subject field,
330 * if needed.
331 */
332
333 static int
334 get_fields (char *datesw, int msg, struct smsg *smsg)
335 {
336 int state;
337 int compnum;
338 char *msgnam, buf[NMH_BUFSIZ], nam[NAMESZ];
339 struct tws *tw;
340 char *datecomp = NULL, *subjcomp = NULL;
341 FILE *in;
342 m_getfld_state_t gstate;
343
344 if ((in = fopen (msgnam = m_name (msg), "r")) == NULL) {
345 admonish (msgnam, "unable to read message");
346 return (0);
347 }
348 gstate = m_getfld_state_init(in);
349 for (compnum = 1;;) {
350 int bufsz = sizeof buf;
351 switch (state = m_getfld2(&gstate, nam, buf, &bufsz)) {
352 case FLD:
353 case FLDPLUS:
354 compnum++;
355 if (!strcasecmp (nam, datesw)) {
356 datecomp = add (buf, datecomp);
357 while (state == FLDPLUS) {
358 bufsz = sizeof buf;
359 state = m_getfld2(&gstate, nam, buf, &bufsz);
360 datecomp = add (buf, datecomp);
361 }
362 if (!subjsort || subjcomp)
363 break;
364 } else if (subjsort && !strcasecmp (nam, subjsort)) {
365 subjcomp = add (buf, subjcomp);
366 while (state == FLDPLUS) {
367 bufsz = sizeof buf;
368 state = m_getfld2(&gstate, nam, buf, &bufsz);
369 subjcomp = add (buf, subjcomp);
370 }
371 if (datecomp)
372 break;
373 } else {
374 /* just flush this guy */
375 while (state == FLDPLUS) {
376 bufsz = sizeof buf;
377 state = m_getfld2(&gstate, nam, buf, &bufsz);
378 }
379 }
380 continue;
381
382 case BODY:
383 case FILEEOF:
384 break;
385
386 case LENERR:
387 case FMTERR:
388 if (state == LENERR || state == FMTERR) {
389 inform("format error in message %d (header #%d), continuing...",
390 msg, compnum);
391 check_failed = 1;
392 }
393 free(datecomp);
394 free(subjcomp);
395 fclose (in);
396 return (0);
397
398 default:
399 adios (NULL, "internal error -- you lose");
400 }
401 break;
402 }
403 m_getfld_state_destroy (&gstate);
404
405 /*
406 * If no date component, then use the modification
407 * time of the file as its date
408 */
409 if (!datecomp || (tw = dparsetime (datecomp)) == NULL) {
410 struct stat st;
411
412 inform("can't parse %s field in message %d, "
413 "will use file modification time", datesw, msg);
414 fstat (fileno (in), &st);
415 smsg->s_clock = st.st_mtime;
416 check_failed = 1;
417 } else {
418 smsg->s_clock = dmktime (tw);
419 }
420
421 if (subjsort) {
422 if (subjcomp) {
423 /*
424 * try to make the subject "canonical": delete
425 * leading "re:", everything but letters & smash
426 * letters to lower case.
427 */
428 char *cp, *cp2, c;
429
430 cp = subjcomp;
431 cp2 = subjcomp;
432 if (strcmp (subjsort, "subject") == 0) {
433 while ((c = *cp)) {
434 if (! isspace((unsigned char) c)) {
435 if(!uprf(cp, "re:"))
436 break;
437 cp += 2;
438 }
439 cp++;
440 }
441 }
442
443 while ((c = *cp++)) {
444 if (isascii((unsigned char) c) && isalnum((unsigned char) c))
445 *cp2++ = tolower((unsigned char)c);
446 }
447
448 *cp2 = '\0';
449 }
450 else
451 subjcomp = "";
452
453 smsg->s_subj = subjcomp;
454 }
455 fclose (in);
456 free(datecomp);
457
458 return (1);
459 }
460
461 /*
462 * sort on dates.
463 */
464 static int
465 dsort (struct smsg **a, struct smsg **b)
466 {
467 if ((*a)->s_clock < (*b)->s_clock)
468 return (-1);
469 if ((*a)->s_clock > (*b)->s_clock)
470 return (1);
471 if ((*a)->s_msg < (*b)->s_msg)
472 return (-1);
473 return (1);
474 }
475
476 /*
477 * sort on subjects.
478 */
479 static int
480 subsort (struct smsg **a, struct smsg **b)
481 {
482 int i;
483
484 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
485 return (i);
486
487 return (dsort (a, b));
488 }
489
490 static int
491 txtsort (struct smsg **a, struct smsg **b)
492 {
493 int i;
494
495 if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
496 return (i);
497 if ((*a)->s_msg < (*b)->s_msg)
498 return (-1);
499 return (1);
500 }
501
502 static void
503 rename_chain (struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
504 {
505 int nxt, old, new;
506 char *newname, oldname[BUFSIZ];
507 char newbuf[PATH_MAX + 1];
508
509 for (;;) {
510 nxt = mlist[msg] - smsgs; /* mlist[msg] is a ptr into smsgs */
511 mlist[msg] = NULL;
512 old = smsgs[nxt].s_msg;
513 new = smsgs[msg].s_msg;
514 strncpy (oldname, m_name (old), sizeof(oldname));
515 newname = m_name (new);
516 if (verbose)
517 printf ("message %d becomes message %d\n", old, new);
518
519 (void)snprintf(oldname, sizeof (oldname), "%s/%d", mp->foldpath, old);
520 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
521 ext_hook("ref-hook", oldname, newbuf);
522
523 if (rename (oldname, newname) == NOTOK)
524 adios (newname, "unable to rename %s to", oldname);
525
526 copy_msg_flags (mp, new, old);
527 if (mp->curmsg == old)
528 seq_setcur (mp, new);
529
530 if (nxt == endmsg)
531 break;
532
533 msg = nxt;
534 }
535 /* if (nxt != endmsg); */
536 /* rename_chain (mp, mlist, nxt, endmsg); */
537 }
538
539 static void
540 rename_msgs (struct msgs *mp, struct smsg **mlist)
541 {
542 int i, j, old, new;
543 bvector_t tmpset = bvector_create ();
544 char f1[BUFSIZ], tmpfil[BUFSIZ];
545 char newbuf[PATH_MAX + 1];
546 struct smsg *sp;
547
548 strncpy (tmpfil, m_name (mp->hghmsg + 1), sizeof(tmpfil));
549
550 for (i = 0; i < nmsgs; i++) {
551 if (! (sp = mlist[i]))
552 continue; /* did this one */
553
554 j = sp - smsgs;
555 if (j == i)
556 continue; /* this one doesn't move */
557
558 /*
559 * the guy that was msg j is about to become msg i.
560 * rename 'j' to make a hole, then recursively rename
561 * guys to fill up the hole.
562 */
563 old = smsgs[j].s_msg;
564 new = smsgs[i].s_msg;
565 strncpy (f1, m_name (old), sizeof(f1));
566
567 if (verbose)
568 printf ("renaming message chain from %d to %d\n", old, new);
569
570 /*
571 * Run the external hook to refile the old message as the
572 * temporary message number that is off of the end of the
573 * messages in the folder.
574 */
575
576 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
577 (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, mp->hghmsg + 1);
578 ext_hook("ref-hook", f1, newbuf);
579
580 if (rename (f1, tmpfil) == NOTOK)
581 adios (tmpfil, "unable to rename %s to ", f1);
582
583 get_msg_flags (mp, tmpset, old);
584
585 rename_chain (mp, mlist, j, i);
586
587 /*
588 * Run the external hook to refile the temporary message number
589 * to the real place.
590 */
591
592 (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
593 ext_hook("ref-hook", newbuf, f1);
594
595 if (rename (tmpfil, m_name(new)) == NOTOK)
596 adios (m_name(new), "unable to rename %s to", tmpfil);
597
598 set_msg_flags (mp, tmpset, new);
599 mp->msgflags |= SEQMOD;
600 }
601
602 bvector_free (tmpset);
603 }