* More IMAP tweaks
[citadel.git] / citadel / imap_tools.c
1 /*
2  * $Id$
3  *
4  * Utility functions for the IMAP module.
5  *
6  */
7
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <stdio.h>
11 #include <ctype.h>
12 #include <string.h>
13 #include "citadel.h"
14 #include "sysdep_decls.h"
15 #include "tools.h"
16 #include "imap_tools.h"
17
18
19 /*
20  * Output a string to the IMAP client, either as a literal or quoted.
21  * (We do a literal if it has any double-quotes or backslashes.)
22  */
23 void imap_strout(char *buf) {
24         int i;
25         int is_literal = 0;
26
27         if (buf == NULL) {              /* yeah, we handle this */
28                 cprintf("NIL");
29                 return;
30         }
31
32         for (i=0; i<strlen(buf); ++i) {
33                 if ( (buf[i]=='\"') || (buf[i]=='\\') ) is_literal = 1;
34         }
35
36         if (is_literal) {
37                 cprintf("{%d}\r\n%s", strlen(buf), buf);
38         }
39
40         else {
41                 cprintf("\"%s\"", buf);
42         }
43 }
44
45         
46
47
48
49 /*
50  * Break a command down into tokens, taking into consideration the
51  * possibility of escaping spaces using quoted tokens
52  */
53 int imap_parameterize(char **args, char *buf) {
54         int num = 0;
55         int start = 0;
56         int i;
57         int in_quote = 0;
58         int original_len;
59
60         strcat(buf, " ");
61
62         original_len = strlen(buf);
63
64         for (i=0; i<original_len; ++i) {
65
66                 if ( (isspace(buf[i])) && (!in_quote) ) {
67                         buf[i] = 0;
68                         args[num] = &buf[start];
69                         start = i+1;
70                         if (args[num][0] == '\"') {
71                                 ++args[num];
72                                 args[num][strlen(args[num])-1] = 0;
73                         }
74                         ++num;
75                 }
76
77                 else if ( (buf[i] == '\"') && (!in_quote) ) {
78                         in_quote = 1;
79                 }
80
81                 else if ( (buf[i] == '\"') && (in_quote) ) {
82                         in_quote = 0;
83                 }
84
85         }
86
87         return(num);
88 }
89                         
90 /*
91  * Convert a struct quickroom to an IMAP-compatible mailbox name.
92  */
93 void imap_mailboxname(char *buf, int bufsize, struct quickroom *qrbuf) {
94
95         safestrncpy(buf, qrbuf->QRname, bufsize);
96         if (qrbuf->QRflags & QR_MAILBOX) {
97                 strcpy(buf, &buf[11]);
98                 if (!strcasecmp(buf, MAILROOM)) strcpy(buf, "INBOX");
99         }
100 }
101