]> diplodocus.org Git - nmh/blob - sbr/seq_list.c
Fix invalid pointer arithmetic.
[nmh] / sbr / seq_list.c
1 /* seq_list.c -- Get all messages in a sequence and return them
2 * -- as a space separated list of message ranges.
3 *
4 * This code is Copyright (c) 2002, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
7 */
8
9 #include <h/mh.h>
10 #include <h/utils.h>
11
12 /* allocate this much buffer space at a time */
13 #define MAXBUFFER 1024
14
15 /* static buffer to collect the sequence line */
16 static char *buffer = NULL;
17 static int len = 0;
18
19
20 char *
21 seq_list(struct msgs *mp, char *seqname)
22 {
23 int i, j, seqnum;
24 char *bp;
25
26 /* On first invocation, allocate initial buffer space */
27 if (!buffer) {
28 len = MAXBUFFER;
29 buffer = mh_xmalloc ((size_t) len);
30 }
31
32 /*
33 * Special processing for "cur" sequence. We assume that the
34 * "cur" sequence and mp->curmsg are in sync (see seq_add.c).
35 * This is returned, even if message doesn't exist or the
36 * folder is empty.
37 */
38 if (!strcmp (current, seqname)) {
39 if (mp->curmsg) {
40 snprintf(buffer, len, "%s", m_name(mp->curmsg));
41 return buffer;
42 }
43 return NULL;
44 }
45
46 /* If the folder is empty, just return NULL */
47 if (mp->nummsg == 0)
48 return NULL;
49
50 /* Get the index of the sequence */
51 if ((seqnum = seq_getnum (mp, seqname)) == -1)
52 return NULL;
53
54 bp = buffer;
55
56 for (i = mp->lowmsg; i <= mp->hghmsg; ++i) {
57 /*
58 * If message doesn't exist, or isn't in
59 * the sequence, then continue.
60 */
61 if (!does_exist(mp, i) || !in_sequence(mp, seqnum, i))
62 continue;
63
64 /*
65 * See if we need to enlarge buffer. Since we don't know
66 * exactly how many character this particular message range
67 * will need, we enlarge the buffer if we are within
68 * 50 characters of the end.
69 */
70 if (bp - buffer > len - 50) {
71 char *newbuf;
72
73 len += MAXBUFFER;
74 newbuf = mh_xrealloc (buffer, (size_t) len);
75 bp = newbuf + (bp - buffer);
76 buffer = newbuf;
77 }
78
79 /*
80 * If this is not the first message range in
81 * the list, first add a space.
82 */
83 if (bp > buffer)
84 *bp++ = ' ';
85
86 strcpy(bp, m_name(i));
87 bp += strlen(bp);
88 j = i; /* Remember beginning of message range */
89
90 /*
91 * Scan to the end of this message range
92 */
93 for (++i; i <= mp->hghmsg && does_exist(mp, i) && in_sequence(mp, seqnum, i);
94 ++i)
95 ;
96
97 if (i - j > 1) {
98 *bp++ = '-';
99 strcpy(bp, m_name(i - 1));
100 bp += strlen(bp);
101 }
102 }
103 return bp > buffer ? buffer : NULL;
104 }