2 * Utility functions for the IMAP module.
4 * Copyright (c) 2001-2009 by the citadel.org team and others, except for
5 * most of the UTF7 and UTF8 handling code which was lifted from Evolution.
7 * This program is open source software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #define SHOW_ME_VAPPEND_PRINTF
29 #include <libcitadel.h>
31 #include "sysdep_decls.h"
32 #include "internet_addressing.h"
33 #include "serv_imap.h"
34 #include "imap_tools.h"
35 #include "ctdl_module.h"
41 /* String handling helpers */
43 /* This code uses some pretty nasty string manipulation. To make everything
44 * manageable, we use this semi-high-level string manipulation API. Strings are
45 * always \0-terminated, despite the fact that we keep track of the size.
53 static void string_init(struct string* s, char* buf, int bufsize)
56 s->maxsize = bufsize-1;
57 s->size = strlen(buf);
60 static char* string_end(struct string* s)
62 return s->buffer + s->size;
65 /* Append a UTF8 string of a particular length (in bytes). -1 to autocalculate. */
67 static void string_append_sn(struct string* s, char* p, int len)
71 if ((s->size+len) > s->maxsize)
72 len = s->maxsize - s->size;
73 memcpy(s->buffer + s->size, p, len);
75 s->buffer[s->size] = '\0';
78 /* As above, always autocalculate. */
80 #define string_append_s(s, p) string_append_sn((s), (p), -1)
82 /* Appends a UTF8 character --- which may make the size change by more than 1!
83 * If the string overflows, the last character may become invalid. */
85 static void string_append_c(struct string* s, int c)
90 /* Don't do anything if there's no room. */
92 if (s->size == s->maxsize)
97 /* This is the most common case, so we optimise it. */
99 s->buffer[s->size++] = c;
100 s->buffer[s->size] = 0;
105 UmlChar[0] = 0xC0 | (c >> 6);
106 UmlChar[1] = 0x80 | (c & 0x3F);
109 else if (c <= 0xFFFF)
111 UmlChar[0] = 0xE0 | (c >> 12);
112 UmlChar[1] = 0x80 | ((c >> 6) & 0x3f);
113 UmlChar[2] = 0x80 | (c & 0x3f);
118 UmlChar[0] = 0xf0 | c >> 18;
119 UmlChar[1] = 0x80 | ((c >> 12) & 0x3f);
120 UmlChar[2] = 0x80 | ((c >> 6) & 0x3f);
121 UmlChar[3] = 0x80 | (c & 0x3f);
125 string_append_sn(s, UmlChar, len);
128 /* Reads a UTF8 character from a char*, advancing the pointer. */
130 int utf8_getc(char** ptr)
132 unsigned char* p = (unsigned char*) *ptr;
148 /* valid start char? (max 4 octets) */
150 m = 0x7f80; /* used to mask out the length bits */
153 if ((c & 0xc0) != 0x80)
158 v = (v<<6) | (c & 0x3f);
173 /* IMAP name safety */
175 /* IMAP has certain special requirements in its character set, which means we
176 * have to do a fair bit of work to convert Citadel's UTF8 strings to IMAP
177 * strings. The next two routines (and their data tables) do that.
180 static char *utf7_alphabet =
181 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
183 static unsigned char utf7_rank[256] = {
184 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
185 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
186 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x3E,0x3F,0xFF,0xFF,0xFF,
187 0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
188 0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,
189 0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF,
190 0xFF,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
191 0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0xFF,0xFF,0xFF,0xFF,0xFF,
192 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
193 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
194 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
195 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
196 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
197 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
198 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
199 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
202 /* Base64 helpers. */
204 static void utf7_closeb64(struct string* out, int v, int i)
210 x = (v << (6-i)) & 0x3F;
211 string_append_c(out, utf7_alphabet[x]);
213 string_append_c(out, '-');
216 /* Convert from a Citadel name to an IMAP-safe name. Returns the end
217 * of the destination.
219 static char* toimap(char* destp, char* destend, char* src)
227 string_init(&dest, destp, destend-destp);
228 /* IMAP_syslog(LOG_DEBUG, "toimap %s", src); */
232 int c = utf8_getc(&src);
236 if (c >= 0x20 && c <= 0x7e)
240 utf7_closeb64(&dest, v, i);
248 string_append_sn(&dest, "&-", 2);
252 /* Citadel extension: / becomes |, because /
253 * isn't valid as part of an IMAP name. */
259 /* Citadel extension: backslashes mark folder
260 * seperators in the IMAP subfolder emulation
261 * hack. We turn them into / characters,
262 * *except* if it's the last character in the
271 string_append_c(&dest, c);
278 string_append_c(&dest, '&');
285 int x = (v >> (i-6)) & 0x3f;
286 string_append_c(&dest, utf7_alphabet[x]);
293 utf7_closeb64(&dest, v, i);
294 /* IMAP_syslog(LOG_DEBUG, " -> %s", destp); */
295 return string_end(&dest);
298 /* Convert from an IMAP-safe name back into a Citadel name. Returns the end of the destination. */
300 static int cfrommap(int c);
301 static char* fromimap(char* destp, char* destend, const char* src)
304 unsigned const char *p = (unsigned const char*) src;
311 string_init(&dest, destp, destend-destp);
312 /* IMAP_syslog(LOG_DEBUG, "fromimap %s", src); */
319 /* US-ASCII characters. */
324 string_append_c(&dest, cfrommap(c));
330 string_append_c(&dest, '&');
333 else if (utf7_rank[c] != 0xff)
342 string_append_sn(&dest, "&-", 2);
350 else if (utf7_rank[c] != 0xFF)
352 v = (v<<6) | utf7_rank[c];
356 int x = (v >> (i-16)) & 0xFFFF;
357 string_append_c(&dest, cfrommap(x));
363 string_append_c(&dest, cfrommap(c));
370 /* IMAP_syslog(LOG_DEBUG, " -> %s", destp); */
371 return string_end(&dest);
374 /* Undoes the special character conversion. */
376 static int cfrommap(int c)
380 case '|': return '/';
381 case '/': return '\\';
389 /* Break a command down into tokens, unquoting any escaped characters. */
391 void MakeStringOf(StrBuf *Buf, int skip)
394 citimap_command *Cmd = &IMAP->Cmd;
396 for (i=skip; i<Cmd->num_parms; ++i) {
397 StrBufAppendBufPlain(Buf, Cmd->Params[i].Key, Cmd->Params[i].len, 0);
398 if (i < (Cmd->num_parms-1)) StrBufAppendBufPlain(Buf, HKEY(" "), 0);
403 void TokenCutRight(citimap_command *Cmd,
409 if (CutMe->len < n) {
414 CutAt = CutMe->Key + CutMe->len - n;
417 StrBufPeek(Cmd->CmdBuf, CutAt, -1, '\0');
420 void TokenCutLeft(citimap_command *Cmd,
424 if (CutMe->len < n) {
425 CutMe->Key += CutMe->len;
436 int CmdAdjust(citimap_command *Cmd,
441 if (nArgs > Cmd->avail_parms) {
442 Params = (ConstStr*) malloc(sizeof(ConstStr) * nArgs);
446 sizeof(ConstStr) * Cmd->avail_parms);
449 sizeof(ConstStr) * Cmd->avail_parms,
451 sizeof(ConstStr) * nArgs -
452 sizeof(ConstStr) * Cmd->avail_parms
458 sizeof(ConstStr) * nArgs);
460 Cmd->avail_parms = nArgs;
461 if (Cmd->Params != NULL)
463 Cmd->Params = Params;
469 sizeof(ConstStr) * Cmd->avail_parms);
473 return Cmd->avail_parms;
476 int imap_parameterize(citimap_command *Cmd)
479 const char *In, *End;
481 In = ChrPtr(Cmd->CmdBuf);
482 End = In + StrLength(Cmd->CmdBuf);
484 /* we start with 10 chars per arg, maybe we need to realloc later. */
485 nArgs = StrLength(Cmd->CmdBuf) / 10 + 10;
486 nArgs = CmdAdjust(Cmd, nArgs, 0);
489 /* Skip whitespace. */
495 /* Found the start of a token. */
497 Cmd->Params[Cmd->num_parms].Key = In;
499 /* Read in the token. */
508 /* Found a quoted section. */
510 Cmd->Params[Cmd->num_parms].Key++;
516 StrBufPeek(Cmd->CmdBuf, In, -1, '\0');
519 else if (*In == '\\')
523 Cmd->Params[Cmd->num_parms].len =
524 In - Cmd->Params[Cmd->num_parms].Key;
526 return Cmd->num_parms;
531 else if (*In == '\\')
537 Cmd->Params[Cmd->num_parms].len =
538 In - Cmd->Params[Cmd->num_parms].Key;
540 return Cmd->num_parms;
544 StrBufPeek(Cmd->CmdBuf, In, -1, '\0');
545 Cmd->Params[Cmd->num_parms].len =
546 In - Cmd->Params[Cmd->num_parms].Key;
547 if (Cmd->num_parms + 1 >= Cmd->avail_parms) {
548 nArgs = CmdAdjust(Cmd, nArgs * 2, 1);
553 return Cmd->num_parms;
557 /* Convert a struct ctdlroom to an IMAP-compatible mailbox name. */
559 void imap_mailboxname(char *buf, int bufsize, struct ctdlroom *qrbuf)
561 char* bufend = buf+bufsize;
565 /* For mailboxes, just do it straight.
566 * Do the Cyrus-compatible thing: all private folders are
567 * subfolders of INBOX. */
569 if (qrbuf->QRflags & QR_MAILBOX)
571 if (strcasecmp(qrbuf->QRname+11, MAILROOM) == 0)
572 toimap(p, bufend, "INBOX");
575 p = toimap(p, bufend, "INBOX");
578 toimap(p, bufend, qrbuf->QRname+11);
583 /* Otherwise, prefix the floor name as a "public folders" moniker. */
585 fl = CtdlGetCachedFloor(qrbuf->QRfloor);
586 p = toimap(p, bufend, fl->f_name);
589 toimap(p, bufend, qrbuf->QRname);
594 * Convert an inputted folder name to our best guess as to what an equivalent
595 * room name should be.
597 * If an error occurs, it returns -1. Otherwise...
599 * The lower eight bits of the return value are the floor number on which the
600 * room most likely resides. The upper eight bits may contain flags,
601 * including IR_MAILBOX if we're dealing with a personal room.
605 int imap_roomname(char *rbuf, int bufsize, const char *foldername)
607 struct CitContext *CCC = CC;
609 char floorname[ROOMNAMELEN*2];
610 char roomname[ROOMNAMELEN];
615 if (foldername == NULL)
618 /* Unmunge the entire string into the output buffer. */
620 fromimap(rbuf, rbuf+bufsize, foldername);
622 /* Is this an IMAP inbox? */
624 if (strncasecmp(rbuf, "INBOX", 5) == 0)
628 /* It's the system inbox. */
630 safestrncpy(rbuf, MAILROOM, bufsize);
631 ret = (0 | IR_MAILBOX);
634 else if (rbuf[5] == FDELIM)
636 /* It's another personal mail folder. */
638 safestrncpy(rbuf, rbuf+6, bufsize);
639 ret = (0 | IR_MAILBOX);
643 /* If we get here, the folder just happens to start with INBOX
644 * --- fall through. */
647 /* Is this a multi-level room name? */
649 levels = num_tokens(rbuf, FDELIM);
653 /* Extract the main room name. */
655 len = extract_token(floorname, rbuf, 0, FDELIM, sizeof floorname);
656 if (len < 0) len = 0;
657 safestrncpy(roomname, &rbuf[len + 1], sizeof(roomname));
659 /* Try and find it on any floor. */
661 for (i = 0; i < MAXFLOORS; ++i)
663 fl = CtdlGetCachedFloor(i);
664 if (fl->f_flags & F_INUSE)
666 if (strcasecmp(floorname, fl->f_name) == 0)
670 safestrncpy(rbuf, roomname, bufsize);
678 /* Meh. It's either not a multi-level room name, or else we
681 ret = (0 | IR_MAILBOX);
684 IMAP_syslog(LOG_DEBUG, "(That translates to \"%s\")", rbuf);
689 * Output a struct internet_address_list in the form an IMAP client wants
691 void imap_ial_out(struct internet_address_list *ialist)
693 struct internet_address_list *iptr;
695 if (ialist == NULL) {
701 for (iptr = ialist; iptr != NULL; iptr = iptr->next) {
703 plain_imap_strout(iptr->ial_name);
705 plain_imap_strout(iptr->ial_user);
707 plain_imap_strout(iptr->ial_node);
717 * Determine whether the supplied string is a valid message set.
718 * If the string contains only numbers, colons, commas, and asterisks,
719 * return 1 for a valid message set. If any other character is found,
722 int imap_is_message_set(const char *buf)
727 return (0); /* stupidity checks */
731 if (!strcasecmp(buf, "ALL"))
732 return (1); /* macro? why? */
734 for (i = 0; buf[i]; ++i) { /* now start the scan */
744 return (1); /* looks like we're good */
749 * imap_match.c, based on wildmat.c from INN
750 * hacked for Citadel/IMAP by Daniel Malament
753 /* note: not all return statements use these; don't change them */
754 #define WILDMAT_TRUE 1
755 #define WILDMAT_FALSE 0
756 #define WILDMAT_ABORT -1
757 #define WILDMAT_DELIM '/'
760 * Match text and p, return TRUE, FALSE, or ABORT.
762 static int do_imap_match(const char *supplied_text, const char *supplied_p)
765 char lcase_text[SIZ], lcase_p[SIZ];
769 /* Copy both strings and lowercase them, in order to
770 * make this entire operation case-insensitive.
773 ((supplied_text[i] != '\0') &&
774 (i < sizeof(lcase_text)));
776 lcase_text[i] = tolower(supplied_text[i]);
777 lcase_text[i] = '\0';
780 ((supplied_p[i] != '\0') &&
781 (i < sizeof(lcase_p)));
783 lcase_p[i] = tolower(supplied_p[i]);
787 for (p = lcase_p, text = lcase_text;
788 !IsEmptyStr(p) && !IsEmptyStr(text);
790 if ((*text == '\0') && (*p != '*') && (*p != '%')) {
791 return WILDMAT_ABORT;
796 return WILDMAT_FALSE;
801 while (++p, ((*p == '*') || (*p == '%'))) {
802 /* Consecutive stars or %'s act
803 * just like one star.
808 /* Trailing star matches everything. */
812 if ((matched = do_imap_match(text++, p))
817 return WILDMAT_ABORT;
819 while (++p, (!IsEmptyStr(p) && ((*p == '*') || (*p == '%'))))
821 /* Consecutive %'s act just like one, but even
822 * a single star makes the sequence act like
832 * Trailing % matches everything
833 * without a delimiter.
835 while (!IsEmptyStr(text)) {
836 if (*text == WILDMAT_DELIM) {
837 return WILDMAT_FALSE;
843 while (!IsEmptyStr(text) &&
844 /* make shure texst - 1 isn't before lcase_p */
845 ((text == lcase_text) || (*(text - 1) != WILDMAT_DELIM)))
847 if ((matched = do_imap_match(text++, p))
852 return WILDMAT_ABORT;
856 if ((*text == '\0') && (*p == '\0')) return WILDMAT_TRUE;
857 else return WILDMAT_FALSE;
863 * Support function for mailbox pattern name matching in LIST and LSUB
864 * Returns nonzero if the supplied mailbox name matches the supplied pattern.
866 int imap_mailbox_matches_pattern(const char *pattern, char *mailboxname)
868 /* handle just-star case quickly */
869 if ((pattern[0] == '*') && (pattern[1] == '\0')) {
872 return (do_imap_match(mailboxname, pattern) == WILDMAT_TRUE);
878 * Compare an IMAP date string (date only, no time) to the date found in
881 int imap_datecmp(const char *datestr, time_t msgtime) {
886 int day, month, year;
887 int msgday, msgmonth, msgyear;
890 char *imap_datecmp_ascmonths[12] = {
891 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
894 if (datestr == NULL) return(0);
896 /* Expecting a date in the form dd-Mmm-yyyy */
897 extract_token(daystr, datestr, 0, '-', sizeof daystr);
898 extract_token(monthstr, datestr, 1, '-', sizeof monthstr);
899 extract_token(yearstr, datestr, 2, '-', sizeof yearstr);
902 year = atoi(yearstr);
904 for (i=0; i<12; ++i) {
905 if (!strcasecmp(monthstr, imap_datecmp_ascmonths[i])) {
910 /* Extract day/month/year from message timestamp */
911 localtime_r(&msgtime, &msgtm);
912 msgday = msgtm.tm_mday;
913 msgmonth = msgtm.tm_mon;
914 msgyear = msgtm.tm_year + 1900;
916 /* Now start comparing */
918 if (year < msgyear) return(+1);
919 if (year > msgyear) return(-1);
921 if (month < msgmonth) return(+1);
922 if (month > msgmonth) return(-1);
924 if (day < msgday) return(+1);
925 if (day > msgday) return(-1);
934 void IAPrintf(const char *Format, ...)
938 va_start(arg_ptr, Format);
939 StrBufVAppendPrintf(IMAP->Reply, Format, arg_ptr);
943 void iaputs(const char *Str, long Len)
945 StrBufAppendBufPlain(IMAP->Reply, Str, Len, 0);
948 void ireply(const char *Msg, long len)
950 citimap *Imap = IMAP;
952 StrBufAppendBufPlain(Imap->Reply,
953 CKEY(Imap->Cmd.Params[0]), 0);
954 StrBufAppendBufPlain(Imap->Reply,
956 StrBufAppendBufPlain(Imap->Reply,
959 StrBufAppendBufPlain(Imap->Reply,
964 void IReplyPrintf(const char *Format, ...)
966 citimap *Imap = IMAP;
970 StrBufAppendBufPlain(Imap->Reply,
971 CKEY(Imap->Cmd.Params[0]), 0);
973 StrBufAppendBufPlain(Imap->Reply,
976 va_start(arg_ptr, Format);
977 StrBufVAppendPrintf(IMAP->Reply, Format, arg_ptr);
980 StrBufAppendBufPlain(Imap->Reply,
987 /* Output a string to the IMAP client, either as a literal or quoted.
988 * (We do a literal if it has any double-quotes or backslashes.) */
990 void plain_imap_strout(char *buf)
995 citimap *Imap = IMAP;
997 if (buf == NULL) { /* yeah, we handle this */
1003 for (i = 0; i < Len; ++i) {
1004 if ((buf[i] == '\"') || (buf[i] == '\\'))
1009 StrBufAppendPrintf(Imap->Reply, "{%ld}\r\n", Len);
1010 StrBufAppendBufPlain(Imap->Reply, buf, Len, 0);
1012 StrBufAppendBufPlain(Imap->Reply,
1014 StrBufAppendBufPlain(Imap->Reply,
1016 StrBufAppendBufPlain(Imap->Reply,
1022 /* Output a string to the IMAP client, either as a literal or quoted.
1023 * (We do a literal if it has any double-quotes or backslashes.) */
1026 void IPutStr(const char *Msg, long Len)
1030 citimap *Imap = IMAP;
1033 if ((Msg == NULL) || (Len == 0))
1034 { /* yeah, we handle this */
1035 StrBufAppendBufPlain(Imap->Reply, HKEY("NIL"), 0);
1039 for (i = 0; i < Len; ++i) {
1040 if ((Msg[i] == '\"') || (Msg[i] == '\\'))
1045 StrBufAppendPrintf(Imap->Reply, "{%ld}\r\n", Len);
1046 StrBufAppendBufPlain(Imap->Reply, Msg, Len, 0);
1048 StrBufAppendBufPlain(Imap->Reply,
1050 StrBufAppendBufPlain(Imap->Reply,
1052 StrBufAppendBufPlain(Imap->Reply,
1057 void IUnbuffer (void)
1059 citimap *Imap = IMAP;
1061 cputbuf(Imap->Reply);
1062 FlushStrBuf(Imap->Reply);