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 free 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
27 #include <libcitadel.h>
29 #include "sysdep_decls.h"
30 #include "internet_addressing.h"
31 #include "imap_tools.h"
32 #include "serv_imap.h"
33 #include "ctdl_module.h"
39 /* String handling helpers */
41 /* This code uses some pretty nasty string manipulation. To make everything
42 * manageable, we use this semi-high-level string manipulation API. Strings are
43 * always \0-terminated, despite the fact that we keep track of the size.
51 static void string_init(struct string* s, char* buf, int bufsize)
54 s->maxsize = bufsize-1;
55 s->size = strlen(buf);
58 static char* string_end(struct string* s)
60 return s->buffer + s->size;
63 /* Append a UTF8 string of a particular length (in bytes). -1 to autocalculate. */
65 static void string_append_sn(struct string* s, char* p, int len)
69 if ((s->size+len) > s->maxsize)
70 len = s->maxsize - s->size;
71 memcpy(s->buffer + s->size, p, len);
73 s->buffer[s->size] = '\0';
76 /* As above, always autocalculate. */
78 #define string_append_s(s, p) string_append_sn((s), (p), -1)
80 /* Appends a UTF8 character --- which may make the size change by more than 1!
81 * If the string overflows, the last character may become invalid. */
83 static void string_append_c(struct string* s, int c)
88 /* Don't do anything if there's no room. */
90 if (s->size == s->maxsize)
95 /* This is the most common case, so we optimise it. */
97 s->buffer[s->size++] = c;
98 s->buffer[s->size] = 0;
103 UmlChar[0] = 0xC0 | (c >> 6);
104 UmlChar[1] = 0x80 | (c & 0x3F);
107 else if (c <= 0xFFFF)
109 UmlChar[0] = 0xE0 | (c >> 12);
110 UmlChar[1] = 0x80 | ((c >> 6) & 0x3f);
111 UmlChar[2] = 0x80 | (c & 0x3f);
116 UmlChar[0] = 0xf0 | c >> 18;
117 UmlChar[1] = 0x80 | ((c >> 12) & 0x3f);
118 UmlChar[2] = 0x80 | ((c >> 6) & 0x3f);
119 UmlChar[3] = 0x80 | (c & 0x3f);
123 string_append_sn(s, UmlChar, len);
126 /* Reads a UTF8 character from a char*, advancing the pointer. */
128 int utf8_getc(char** ptr)
130 unsigned char* p = (unsigned char*) *ptr;
146 /* valid start char? (max 4 octets) */
148 m = 0x7f80; /* used to mask out the length bits */
151 if ((c & 0xc0) != 0x80)
156 v = (v<<6) | (c & 0x3f);
171 /* IMAP name safety */
173 /* IMAP has certain special requirements in its character set, which means we
174 * have to do a fair bit of work to convert Citadel's UTF8 strings to IMAP
175 * strings. The next two routines (and their data tables) do that.
178 static char *utf7_alphabet =
179 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,";
181 static unsigned char utf7_rank[256] = {
182 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
183 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
184 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x3E,0x3F,0xFF,0xFF,0xFF,
185 0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
186 0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,
187 0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF,
188 0xFF,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
189 0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31,0x32,0x33,0xFF,0xFF,0xFF,0xFF,0xFF,
190 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
191 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,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,
200 /* Base64 helpers. */
202 static void utf7_closeb64(struct string* out, int v, int i)
208 x = (v << (6-i)) & 0x3F;
209 string_append_c(out, utf7_alphabet[x]);
211 string_append_c(out, '-');
214 /* Convert from a Citadel name to an IMAP-safe name. Returns the end
215 * of the destination.
217 static char* toimap(char* destp, char* destend, char* src)
225 string_init(&dest, destp, destend-destp);
226 /* CtdlLogPrintf(CTDL_DEBUG, "toimap %s\r\n", src); */
230 int c = utf8_getc(&src);
234 if (c >= 0x20 && c <= 0x7e)
238 utf7_closeb64(&dest, v, i);
246 string_append_sn(&dest, "&-", 2);
250 /* Citadel extension: / becomes |, because /
251 * isn't valid as part of an IMAP name. */
257 /* Citadel extension: backslashes mark folder
258 * seperators in the IMAP subfolder emulation
259 * hack. We turn them into / characters,
260 * *except* if it's the last character in the
269 string_append_c(&dest, c);
276 string_append_c(&dest, '&');
283 int x = (v >> (i-6)) & 0x3f;
284 string_append_c(&dest, utf7_alphabet[x]);
291 utf7_closeb64(&dest, v, i);
292 /* CtdlLogPrintf(CTDL_DEBUG, " -> %s\r\n", destp); */
293 return string_end(&dest);
296 /* Convert from an IMAP-safe name back into a Citadel name. Returns the end of the destination. */
298 static int cfrommap(int c);
299 static char* fromimap(char* destp, char* destend, const char* src)
302 unsigned const char *p = (unsigned const char*) src;
309 string_init(&dest, destp, destend-destp);
310 /* CtdlLogPrintf(CTDL_DEBUG, "fromimap %s\r\n", src); */
317 /* US-ASCII characters. */
322 string_append_c(&dest, cfrommap(c));
328 string_append_c(&dest, '&');
331 else if (utf7_rank[c] != 0xff)
340 string_append_sn(&dest, "&-", 2);
348 else if (utf7_rank[c] != 0xFF)
350 v = (v<<6) | utf7_rank[c];
354 int x = (v >> (i-16)) & 0xFFFF;
355 string_append_c(&dest, cfrommap(x));
361 string_append_c(&dest, cfrommap(c));
368 /* CtdlLogPrintf(CTDL_DEBUG, " -> %s\r\n", destp); */
369 return string_end(&dest);
372 /* Undoes the special character conversion. */
374 static int cfrommap(int c)
378 case '|': return '/';
379 case '/': return '\\';
384 /* Output a string to the IMAP client, either as a literal or quoted.
385 * (We do a literal if it has any double-quotes or backslashes.) */
387 void plain_imap_strout(char *buf)
393 if (buf == NULL) { /* yeah, we handle this */
399 for (i = 0; i < len; ++i) {
400 if ((buf[i] == '\"') || (buf[i] == '\\'))
405 cprintf("{%ld}\r\n%s", len, buf);
407 cprintf("\"%s\"", buf);
411 /* Output a string to the IMAP client, either as a literal or quoted.
412 * (We do a literal if it has any double-quotes or backslashes.) */
414 void imap_strout(ConstStr *args)
419 if ((args == NULL) || (args->len == 0))
420 { /* yeah, we handle this */
425 for (i = 0; i < args->len; ++i) {
426 if ((args->Key[i] == '\"') || (args->Key[i] == '\\'))
431 cprintf("{%ld}\r\n%s", args->len, args->Key);
433 cprintf("\"%s\"", args->Key);
440 /* Break a command down into tokens, unquoting any escaped characters. */
442 void MakeStringOf(StrBuf *Buf, int skip)
445 citimap_command *Cmd = &IMAP->Cmd;
447 for (i=skip; i<Cmd->num_parms; ++i) {
448 StrBufAppendBufPlain(Buf, Cmd->Params[i].Key, Cmd->Params[i].len, 0);
449 if (i < (Cmd->num_parms-1)) StrBufAppendBufPlain(Buf, HKEY(" "), 0);
454 void TokenCutRight(citimap_command *Cmd,
460 if (CutMe->len < n) {
465 CutAt = CutMe->Key + CutMe->len - n;
468 StrBufPeek(Cmd->CmdBuf, CutAt, -1, '\0');
471 void TokenCutLeft(citimap_command *Cmd,
475 if (CutMe->len < n) {
476 CutMe->Key += CutMe->len;
487 int CmdAdjust(citimap_command *Cmd,
492 if (nArgs > Cmd->avail_parms) {
493 Params = (ConstStr*) malloc(sizeof(ConstStr) * nArgs);
497 sizeof(ConstStr) * Cmd->avail_parms);
500 sizeof(ConstStr) * Cmd->avail_parms,
502 sizeof(ConstStr) * nArgs -
503 sizeof(ConstStr) * Cmd->avail_parms
509 sizeof(ConstStr) * nArgs);
511 Cmd->avail_parms = nArgs;
512 if (Cmd->Params != NULL)
514 Cmd->Params = Params;
520 sizeof(ConstStr) * Cmd->avail_parms);
524 return Cmd->avail_parms;
527 int imap_parameterize(citimap_command *Cmd)
530 const char *In, *End;
532 In = ChrPtr(Cmd->CmdBuf);
533 End = In + StrLength(Cmd->CmdBuf);
535 /* we start with 10 chars per arg, maybe we need to realloc later. */
536 nArgs = StrLength(Cmd->CmdBuf) / 10 + 10;
537 nArgs = CmdAdjust(Cmd, nArgs, 0);
540 /* Skip whitespace. */
546 /* Found the start of a token. */
548 Cmd->Params[Cmd->num_parms].Key = In;
550 /* Read in the token. */
559 /* Found a quoted section. */
561 Cmd->Params[Cmd->num_parms].Key++;
567 StrBufPeek(Cmd->CmdBuf, In, -1, '\0');
570 else if (*In == '\\')
574 Cmd->Params[Cmd->num_parms].len =
575 In - Cmd->Params[Cmd->num_parms].Key;
577 return Cmd->num_parms;
582 else if (*In == '\\')
588 Cmd->Params[Cmd->num_parms].len =
589 In - Cmd->Params[Cmd->num_parms].Key;
591 return Cmd->num_parms;
595 StrBufPeek(Cmd->CmdBuf, In, -1, '\0');
596 Cmd->Params[Cmd->num_parms].len =
597 In - Cmd->Params[Cmd->num_parms].Key;
598 if (Cmd->num_parms + 1 >= Cmd->avail_parms) {
599 nArgs = CmdAdjust(Cmd, nArgs * 2, 1);
604 return Cmd->num_parms;
608 /* Convert a struct ctdlroom to an IMAP-compatible mailbox name. */
610 void imap_mailboxname(char *buf, int bufsize, struct ctdlroom *qrbuf)
612 char* bufend = buf+bufsize;
616 /* For mailboxes, just do it straight.
617 * Do the Cyrus-compatible thing: all private folders are
618 * subfolders of INBOX. */
620 if (qrbuf->QRflags & QR_MAILBOX)
622 if (strcasecmp(qrbuf->QRname+11, MAILROOM) == 0)
623 p = toimap(p, bufend, "INBOX");
626 p = toimap(p, bufend, "INBOX");
629 p = toimap(p, bufend, qrbuf->QRname+11);
634 /* Otherwise, prefix the floor name as a "public folders" moniker. */
636 fl = CtdlGetCachedFloor(qrbuf->QRfloor);
637 p = toimap(p, bufend, fl->f_name);
640 p = toimap(p, bufend, qrbuf->QRname);
645 * Convert an inputted folder name to our best guess as to what an equivalent
646 * room name should be.
648 * If an error occurs, it returns -1. Otherwise...
650 * The lower eight bits of the return value are the floor number on which the
651 * room most likely resides. The upper eight bits may contain flags,
652 * including IR_MAILBOX if we're dealing with a personal room.
656 int imap_roomname(char *rbuf, int bufsize, const char *foldername)
659 char floorname[ROOMNAMELEN*2];
660 char roomname[ROOMNAMELEN];
665 if (foldername == NULL)
668 /* Unmunge the entire string into the output buffer. */
670 fromimap(rbuf, rbuf+bufsize, foldername);
672 /* Is this an IMAP inbox? */
674 if (strncasecmp(rbuf, "INBOX", 5) == 0)
678 /* It's the system inbox. */
680 safestrncpy(rbuf, MAILROOM, bufsize);
681 ret = (0 | IR_MAILBOX);
684 else if (rbuf[5] == FDELIM)
686 /* It's another personal mail folder. */
688 safestrncpy(rbuf, rbuf+6, bufsize);
689 ret = (0 | IR_MAILBOX);
693 /* If we get here, the folder just happens to start with INBOX
694 * --- fall through. */
697 /* Is this a multi-level room name? */
699 levels = num_tokens(rbuf, FDELIM);
703 /* Extract the main room name. */
705 len = extract_token(floorname, rbuf, 0, FDELIM, sizeof floorname);
706 if (len < 0) len = 0;
707 safestrncpy(roomname, &rbuf[len + 1], sizeof(roomname));
709 /* Try and find it on any floor. */
711 for (i = 0; i < MAXFLOORS; ++i)
713 fl = CtdlGetCachedFloor(i);
714 if (fl->f_flags & F_INUSE)
716 if (strcasecmp(floorname, fl->f_name) == 0)
720 safestrncpy(rbuf, roomname, bufsize);
728 /* Meh. It's either not a multi-level room name, or else we
731 ret = (0 | IR_MAILBOX);
734 CtdlLogPrintf(CTDL_DEBUG, "(That translates to \"%s\")\n", rbuf);
739 * Output a struct internet_address_list in the form an IMAP client wants
741 void imap_ial_out(struct internet_address_list *ialist)
743 struct internet_address_list *iptr;
745 if (ialist == NULL) {
751 for (iptr = ialist; iptr != NULL; iptr = iptr->next) {
753 plain_imap_strout(iptr->ial_name);
755 plain_imap_strout(iptr->ial_user);
757 plain_imap_strout(iptr->ial_node);
767 * Determine whether the supplied string is a valid message set.
768 * If the string contains only numbers, colons, commas, and asterisks,
769 * return 1 for a valid message set. If any other character is found,
772 int imap_is_message_set(const char *buf)
777 return (0); /* stupidity checks */
781 if (!strcasecmp(buf, "ALL"))
782 return (1); /* macro? why? */
784 for (i = 0; buf[i]; ++i) { /* now start the scan */
794 return (1); /* looks like we're good */
799 * imap_match.c, based on wildmat.c from INN
800 * hacked for Citadel/IMAP by Daniel Malament
803 /* note: not all return statements use these; don't change them */
804 #define WILDMAT_TRUE 1
805 #define WILDMAT_FALSE 0
806 #define WILDMAT_ABORT -1
807 #define WILDMAT_DELIM '/'
810 * Match text and p, return TRUE, FALSE, or ABORT.
812 static int do_imap_match(const char *supplied_text, const char *supplied_p)
815 char lcase_text[SIZ], lcase_p[SIZ];
819 /* Copy both strings and lowercase them, in order to
820 * make this entire operation case-insensitive.
823 ((supplied_text[i] != '\0') &&
824 (i < sizeof(lcase_text)));
826 lcase_text[i] = tolower(supplied_text[i]);
827 lcase_text[i] = '\0';
830 ((supplied_p[i] != '\0') &&
831 (i < sizeof(lcase_p)));
833 lcase_p[i] = tolower(supplied_p[i]);
837 for (p = lcase_p, text = lcase_text;
838 !IsEmptyStr(p) && !IsEmptyStr(text);
840 if ((*text == '\0') && (*p != '*') && (*p != '%')) {
841 return WILDMAT_ABORT;
846 return WILDMAT_FALSE;
851 while (++p, ((*p == '*') || (*p == '%'))) {
852 /* Consecutive stars or %'s act
853 * just like one star.
858 /* Trailing star matches everything. */
862 if ((matched = do_imap_match(text++, p))
867 return WILDMAT_ABORT;
869 while (++p, (!IsEmptyStr(p) && ((*p == '*') || (*p == '%'))))
871 /* Consecutive %'s act just like one, but even
872 * a single star makes the sequence act like
882 * Trailing % matches everything
883 * without a delimiter.
885 while (!IsEmptyStr(text)) {
886 if (*text == WILDMAT_DELIM) {
887 return WILDMAT_FALSE;
893 while (!IsEmptyStr(text) && (*(text - 1) != WILDMAT_DELIM)) {
894 if ((matched = do_imap_match(text++, p))
899 return WILDMAT_ABORT;
903 if ((*text == '\0') && (*p == '\0')) return WILDMAT_TRUE;
904 else return WILDMAT_FALSE;
910 * Support function for mailbox pattern name matching in LIST and LSUB
911 * Returns nonzero if the supplied mailbox name matches the supplied pattern.
913 int imap_mailbox_matches_pattern(const char *pattern, char *mailboxname)
915 /* handle just-star case quickly */
916 if ((pattern[0] == '*') && (pattern[1] == '\0')) {
919 return (do_imap_match(mailboxname, pattern) == WILDMAT_TRUE);
925 * Compare an IMAP date string (date only, no time) to the date found in
928 int imap_datecmp(const char *datestr, time_t msgtime) {
933 int day, month, year;
934 int msgday, msgmonth, msgyear;
937 char *imap_datecmp_ascmonths[12] = {
938 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
941 if (datestr == NULL) return(0);
943 /* Expecting a date in the form dd-Mmm-yyyy */
944 extract_token(daystr, datestr, 0, '-', sizeof daystr);
945 extract_token(monthstr, datestr, 1, '-', sizeof monthstr);
946 extract_token(yearstr, datestr, 2, '-', sizeof yearstr);
949 year = atoi(yearstr);
951 for (i=0; i<12; ++i) {
952 if (!strcasecmp(monthstr, imap_datecmp_ascmonths[i])) {
957 /* Extract day/month/year from message timestamp */
958 localtime_r(&msgtime, &msgtm);
959 msgday = msgtm.tm_mday;
960 msgmonth = msgtm.tm_mon;
961 msgyear = msgtm.tm_year + 1900;
963 /* Now start comparing */
965 if (year < msgyear) return(+1);
966 if (year > msgyear) return(-1);
968 if (month < msgmonth) return(+1);
969 if (month > msgmonth) return(-1);
971 if (day < msgday) return(+1);
972 if (day > msgday) return(-1);