If the number of messages in a folder is zero, then don't try to
[mmh] / sbr / escape_display_name.c
1 #include <sys/types.h>
2 #include <h/utils.h>
3 #include <string.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6
7 /* Escape a display name, hopefully per RFC 5322.
8    The argument is assumed to be a pointer to a character array of
9    one-byte characters with enough space to handle the additional
10    characters. */
11 void
12 escape_display_name (char *name) {
13     /* Quote and escape name that contains any specials, as necessary. */
14     if (strpbrk("\"(),.:;<>@[\\]", name)) {
15         size_t len = strlen(name);
16         char *destp, *srcp;
17         size_t destpos, srcpos;
18         /* E.g., 2 characters, "", would require 7, "\"\""\0. */
19         char *tmp = malloc (2*len+3);
20
21         for (destp = tmp, srcp = name, destpos = 0, srcpos = 0;
22              *srcp;
23              ++destp, ++srcp, ++destpos, ++srcpos) {
24             if (srcpos == 0) {
25                 /* Insert initial double quote, if needed. */
26                 if (*srcp != '"') {
27                     *destp++ = '"';
28                     ++destpos;
29                 }
30             } else {
31                 /* Escape embedded, unescaped ". */
32                 if (*srcp == '"'  &&  srcpos < len - 1  &&  *(srcp-1) != '\\') {
33                     *destp++ = '\\';
34                     ++destpos;
35                 }
36             }
37
38             *destp = *srcp;
39
40             /* End of name. */
41             if (srcpos == len - 1) {
42                 /* Insert final double quote, if needed. */
43                 if (*srcp != '"') {
44                     *++destp = '"';
45                     ++destpos;
46                 }
47
48                 *++destp = '\0';
49                 ++destpos;
50             }
51         }
52
53         if (strcmp (tmp, "\"")) {
54             /* assert (strlen(tmp) + 1 == destpos); */
55             strncpy (name, tmp, destpos);
56         } else {
57             /* Handle just " as special case here instead of above. */
58             strcpy (name, "\"\\\"\"");
59         }
60
61         free (tmp);
62     }
63 }