* Gratuitous style cleanup of some of the imap code
[citadel.git] / citadel / modules / imap / serv_imap.c
1 /*
2  * $Id$ 
3  *
4  * IMAP server for the Citadel system
5  * Copyright (C) 2000-2009 by Art Cancro and others.
6  * This code is released under the terms of the GNU General Public License.
7  *
8  * WARNING: the IMAP protocol is badly designed.  No implementation of it
9  * is perfect.  Indeed, with so much gratuitous complexity, *all* IMAP
10  * implementations have bugs.
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 3 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25  */
26
27 #include "sysdep.h"
28 #include <stdlib.h>
29 #include <unistd.h>
30 #include <stdio.h>
31 #include <fcntl.h>
32 #include <signal.h>
33 #include <pwd.h>
34 #include <errno.h>
35 #include <sys/types.h>
36
37 #if TIME_WITH_SYS_TIME
38 # include <sys/time.h>
39 # include <time.h>
40 #else
41 # if HAVE_SYS_TIME_H
42 #  include <sys/time.h>
43 # else
44 #  include <time.h>
45 # endif
46 #endif
47
48 #include <sys/wait.h>
49 #include <ctype.h>
50 #include <string.h>
51 #include <limits.h>
52 #include <libcitadel.h>
53 #include "citadel.h"
54 #include "server.h"
55 #include "citserver.h"
56 #include "support.h"
57 #include "config.h"
58 #include "user_ops.h"
59 #include "policy.h"
60 #include "database.h"
61 #include "msgbase.h"
62 #include "internet_addressing.h"
63 #include "serv_imap.h"
64 #include "imap_tools.h"
65 #include "imap_list.h"
66 #include "imap_fetch.h"
67 #include "imap_search.h"
68 #include "imap_store.h"
69 #include "imap_acl.h"
70 #include "imap_metadata.h"
71 #include "imap_misc.h"
72
73 #include "ctdl_module.h"
74
75
76 /* imap_rename() uses this struct containing list of rooms to rename */
77 struct irl {
78         struct irl *next;
79         char irl_oldroom[ROOMNAMELEN];
80         char irl_newroom[ROOMNAMELEN];
81         int irl_newfloor;
82 };
83
84 /* Data which is passed between imap_rename() and imap_rename_backend() */
85 struct irlparms {
86         char *oldname;
87         char *newname;
88         struct irl **irl;
89 };
90
91
92 /*
93  * If there is a message ID map in memory, free it
94  */
95 void imap_free_msgids(void)
96 {
97         if (IMAP->msgids != NULL) {
98                 free(IMAP->msgids);
99                 IMAP->msgids = NULL;
100                 IMAP->num_msgs = 0;
101                 IMAP->num_alloc = 0;
102         }
103         if (IMAP->flags != NULL) {
104                 free(IMAP->flags);
105                 IMAP->flags = NULL;
106         }
107         IMAP->last_mtime = (-1);
108 }
109
110
111 /*
112  * If there is a transmitted message in memory, free it
113  */
114 void imap_free_transmitted_message(void)
115 {
116         if (IMAP->transmitted_message != NULL) {
117                 free(IMAP->transmitted_message);
118                 IMAP->transmitted_message = NULL;
119                 IMAP->transmitted_length = 0;
120         }
121 }
122
123
124 /*
125  * Set the \Seen, \Recent. and \Answered flags, based on the sequence
126  * sets stored in the visit record for this user/room.  Note that we have
127  * to parse each sequence set manually here, because calling the utility
128  * function is_msg_in_sequence_set() over and over again is too expensive.
129  *
130  * first_msg should be set to 0 to rescan the flags for every message in the
131  * room, or some other value if we're only interested in an incremental
132  * update.
133  */
134 void imap_set_seen_flags(int first_msg)
135 {
136         struct visit vbuf;
137         int i;
138         int num_sets;
139         int s;
140         char setstr[64], lostr[64], histr[64];
141         long lo, hi;
142
143         if (IMAP->num_msgs < 1) return;
144         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
145
146         for (i = first_msg; i < IMAP->num_msgs; ++i) {
147                 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_SEEN;
148                 IMAP->flags[i] |= IMAP_RECENT;
149                 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_ANSWERED;
150         }
151
152         /*
153          * Do the "\Seen" flag.
154          * (Any message not "\Seen" is considered "\Recent".)
155          */
156         num_sets = num_tokens(vbuf.v_seen, ',');
157         for (s=0; s<num_sets; ++s) {
158                 extract_token(setstr, vbuf.v_seen, s, ',', sizeof setstr);
159
160                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
161                 if (num_tokens(setstr, ':') >= 2) {
162                         extract_token(histr, setstr, 1, ':', sizeof histr);
163                         if (!strcmp(histr, "*")) {
164                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
165                         }
166                 } 
167                 else {
168                         strcpy(histr, lostr);
169                 }
170                 lo = atol(lostr);
171                 hi = atol(histr);
172
173                 for (i = first_msg; i < IMAP->num_msgs; ++i) {
174                         if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
175                                 IMAP->flags[i] |= IMAP_SEEN;
176                                 IMAP->flags[i] = IMAP->flags[i] & ~IMAP_RECENT;
177                         }
178                 }
179         }
180
181         /* Do the ANSWERED flag */
182         num_sets = num_tokens(vbuf.v_answered, ',');
183         for (s=0; s<num_sets; ++s) {
184                 extract_token(setstr, vbuf.v_answered, s, ',', sizeof setstr);
185
186                 extract_token(lostr, setstr, 0, ':', sizeof lostr);
187                 if (num_tokens(setstr, ':') >= 2) {
188                         extract_token(histr, setstr, 1, ':', sizeof histr);
189                         if (!strcmp(histr, "*")) {
190                                 snprintf(histr, sizeof histr, "%ld", LONG_MAX);
191                         }
192                 } 
193                 else {
194                         strcpy(histr, lostr);
195                 }
196                 lo = atol(lostr);
197                 hi = atol(histr);
198
199                 for (i = first_msg; i < IMAP->num_msgs; ++i) {
200                         if ((IMAP->msgids[i] >= lo) && (IMAP->msgids[i] <= hi)){
201                                 IMAP->flags[i] |= IMAP_ANSWERED;
202                         }
203                 }
204         }
205
206 }
207
208
209
210 /*
211  * Back end for imap_load_msgids()
212  *
213  * Optimization: instead of calling realloc() to add each message, we
214  * allocate space in the list for REALLOC_INCREMENT messages at a time.  This
215  * allows the mapping to proceed much faster.
216  */
217 void imap_add_single_msgid(long msgnum, void *userdata)
218 {
219
220         ++IMAP->num_msgs;
221         if (IMAP->num_msgs > IMAP->num_alloc) {
222                 IMAP->num_alloc += REALLOC_INCREMENT;
223                 IMAP->msgids = realloc(IMAP->msgids, (IMAP->num_alloc * sizeof(long)) );
224                 IMAP->flags = realloc(IMAP->flags, (IMAP->num_alloc * sizeof(long)) );
225         }
226         IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
227         IMAP->flags[IMAP->num_msgs - 1] = 0;
228 }
229
230
231
232 /*
233  * Set up a message ID map for the current room (folder)
234  */
235 void imap_load_msgids(void)
236 {
237         struct cdbdata *cdbfr;
238
239         if (IMAP->selected == 0) {
240                 CtdlLogPrintf(CTDL_ERR,
241                         "imap_load_msgids() can't run; no room selected\n");
242                 return;
243         }
244
245         imap_free_msgids();     /* If there was already a map, free it */
246
247         /* Load the message list */
248         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
249         if (cdbfr != NULL) {
250                 IMAP->msgids = malloc(cdbfr->len);
251                 memcpy(IMAP->msgids, cdbfr->ptr, cdbfr->len);
252                 IMAP->num_msgs = cdbfr->len / sizeof(long);
253                 IMAP->num_alloc = cdbfr->len / sizeof(long);
254                 cdb_free(cdbfr);
255         }
256
257         if (IMAP->num_msgs) {
258                 IMAP->flags = malloc(IMAP->num_alloc * sizeof(long));
259                 memset(IMAP->flags, 0, (IMAP->num_alloc * sizeof(long)) );
260         }
261
262         imap_set_seen_flags(0);
263 }
264
265
266 /*
267  * Re-scan the selected room (folder) and see if it's been changed at all
268  */
269 void imap_rescan_msgids(void)
270 {
271
272         int original_num_msgs = 0;
273         long original_highest = 0L;
274         int i, j, jstart;
275         int message_still_exists;
276         struct cdbdata *cdbfr;
277         long *msglist = NULL;
278         int num_msgs = 0;
279         int num_recent = 0;
280
281         if (IMAP->selected == 0) {
282                 CtdlLogPrintf(CTDL_ERR, "imap_load_msgids() can't run; no room selected\n");
283                 return;
284         }
285
286         /*
287          * Check to see if the room's contents have changed.
288          * If not, we can avoid this rescan.
289          */
290         CtdlGetRoom(&CC->room, CC->room.QRname);
291         if (IMAP->last_mtime == CC->room.QRmtime) {     /* No changes! */
292                 return;
293         }
294
295         /* Load the *current* message list from disk, so we can compare it
296          * to what we have in memory.
297          */
298         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
299         if (cdbfr != NULL) {
300                 msglist = malloc(cdbfr->len);
301                 if (msglist == NULL) {
302                         CtdlLogPrintf(CTDL_CRIT, "malloc() failed\n");
303                         abort();
304                 }
305                 memcpy(msglist, cdbfr->ptr, (size_t)cdbfr->len);
306                 num_msgs = cdbfr->len / sizeof(long);
307                 cdb_free(cdbfr);
308         } else {
309                 num_msgs = 0;
310         }
311
312         /*
313          * Check to see if any of the messages we know about have been expunged
314          */
315         if (IMAP->num_msgs > 0) {
316                 jstart = 0;
317                 for (i = 0; i < IMAP->num_msgs; ++i) {
318
319                         message_still_exists = 0;
320                         if (num_msgs > 0) {
321                                 for (j = jstart; j < num_msgs; ++j) {
322                                         if (msglist[j] == IMAP->msgids[i]) {
323                                                 message_still_exists = 1;
324                                                 jstart = j;
325                                                 break;
326                                         }
327                                 }
328                         }
329
330                         if (message_still_exists == 0) {
331                                 cprintf("* %d EXPUNGE\r\n", i + 1);
332
333                                 /* Here's some nice stupid nonsense.  When a
334                                  * message is expunged, we have to slide all
335                                  * the existing messages up in the message
336                                  * array.
337                                  */
338                                 --IMAP->num_msgs;
339                                 memcpy(&IMAP->msgids[i],
340                                        &IMAP->msgids[i + 1],
341                                        (sizeof(long) *
342                                         (IMAP->num_msgs - i)));
343                                 memcpy(&IMAP->flags[i],
344                                        &IMAP->flags[i + 1],
345                                        (sizeof(long) *
346                                         (IMAP->num_msgs - i)));
347
348                                 --i;
349                         }
350
351                 }
352         }
353
354         /*
355          * Remember how many messages were here before we re-scanned.
356          */
357         original_num_msgs = IMAP->num_msgs;
358         if (IMAP->num_msgs > 0) {
359                 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
360         } else {
361                 original_highest = 0L;
362         }
363
364         /*
365          * Now peruse the room for *new* messages only.
366          * This logic is probably the cause of Bug # 368
367          * [ http://bugzilla.citadel.org/show_bug.cgi?id=368 ]
368          */
369         if (num_msgs > 0) {
370                 for (j = 0; j < num_msgs; ++j) {
371                         if (msglist[j] > original_highest) {
372                                 imap_add_single_msgid(msglist[j], NULL);
373                         }
374                 }
375         }
376         imap_set_seen_flags(original_num_msgs);
377
378         /*
379          * If new messages have arrived, tell the client about them.
380          */
381         if (IMAP->num_msgs > original_num_msgs) {
382
383                 for (j = 0; j < num_msgs; ++j) {
384                         if (IMAP->flags[j] & IMAP_RECENT) {
385                                 ++num_recent;
386                         }
387                 }
388
389                 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
390                 cprintf("* %d RECENT\r\n", num_recent);
391         }
392
393         if (num_msgs != 0) {
394                 free(msglist);
395         }
396         IMAP->last_mtime = CC->room.QRmtime;
397 }
398
399
400 /*
401  * This cleanup function blows away the temporary memory and files used by
402  * the IMAP server.
403  */
404 void imap_cleanup_function(void)
405 {
406
407         /* Don't do this stuff if this is not a IMAP session! */
408         if (CC->h_command_function != imap_command_loop)
409                 return;
410
411         /* If there is a mailbox selected, auto-expunge it. */
412         if (IMAP->selected) {
413                 imap_do_expunge();
414         }
415
416         CtdlLogPrintf(CTDL_DEBUG, "Performing IMAP cleanup hook\n");
417         imap_free_msgids();
418         imap_free_transmitted_message();
419
420         if (IMAP->cached_rfc822_data != NULL) {
421                 free(IMAP->cached_rfc822_data);
422                 IMAP->cached_rfc822_data = NULL;
423                 IMAP->cached_rfc822_msgnum = (-1);
424                 IMAP->cached_rfc822_withbody = 0;
425         }
426
427         if (IMAP->cached_body != NULL) {
428                 free(IMAP->cached_body);
429                 IMAP->cached_body = NULL;
430                 IMAP->cached_body_len = 0;
431                 IMAP->cached_bodymsgnum = (-1);
432         }
433
434         free(IMAP);
435         CtdlLogPrintf(CTDL_DEBUG, "Finished IMAP cleanup hook\n");
436 }
437
438
439 /*
440  * Does the actual work of the CAPABILITY command (because we need to
441  * output this stuff in other places as well)
442  */
443 void imap_output_capability_string(void) {
444         cprintf("CAPABILITY IMAP4REV1 NAMESPACE ID AUTH=PLAIN AUTH=LOGIN UIDPLUS");
445
446 #ifdef HAVE_OPENSSL
447         if (!CC->redirect_ssl) cprintf(" STARTTLS");
448 #endif
449
450 #ifndef DISABLE_IMAP_ACL
451         cprintf(" ACL");
452 #endif
453
454         /* We are building a partial implementation of METADATA for the sole purpose
455          * of interoperating with the ical/vcard version of the Bynari Insight Connector.
456          * It is not a full RFC5464 implementation, but it should refuse non-Bynari
457          * metadata in a compatible and graceful way.
458          */
459         cprintf(" METADATA");
460
461         /*
462          * LIST-EXTENDED was originally going to be required by the METADATA extension.
463          * It was mercifully removed prior to the finalization of RFC5464.  We started
464          * implementing this but stopped when we learned that it would not be needed.
465          * If you uncomment this declaration you are responsible for writing a lot of new
466          * code.
467          *
468          * cprintf(" LIST-EXTENDED")
469          */
470 }
471
472
473 /*
474  * implements the CAPABILITY command
475  */
476 void imap_capability(int num_parms, char *parms[])
477 {
478         cprintf("* ");
479         imap_output_capability_string();
480         cprintf("\r\n");
481         cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
482 }
483
484
485 /*
486  * Implements the ID command (specified by RFC2971)
487  *
488  * We ignore the client-supplied information, and output a NIL response.
489  * Although this is technically a valid implementation of the extension, it
490  * is quite useless.  It exists only so that we may see which clients are
491  * making use of this extension.
492  * 
493  */
494 void imap_id(int num_parms, char *parms[])
495 {
496         cprintf("* ID NIL\r\n");
497         cprintf("%s OK ID completed\r\n", parms[0]);
498 }
499
500
501 /*
502  * Here's where our IMAP session begins its happy day.
503  */
504 void imap_greeting(void)
505 {
506
507         strcpy(CC->cs_clientname, "IMAP session");
508         CC->session_specific_data = malloc(sizeof(struct citimap));
509         memset(IMAP, 0, sizeof(struct citimap));
510         IMAP->authstate = imap_as_normal;
511         IMAP->cached_rfc822_data = NULL;
512         IMAP->cached_rfc822_msgnum = (-1);
513         IMAP->cached_rfc822_withbody = 0;
514
515         if (CC->nologin)
516         {
517                 cprintf("* BYE; Server busy, try later\r\n");
518                 CC->kill_me = 1;
519                 return;
520         }
521         cprintf("* OK [");
522         imap_output_capability_string();
523         cprintf("] %s IMAP4rev1 %s ready\r\n", config.c_fqdn, CITADEL);
524 }
525
526
527 /*
528  * IMAPS is just like IMAP, except it goes crypto right away.
529  */
530 void imaps_greeting(void) {
531         CtdlModuleStartCryptoMsgs(NULL, NULL, NULL);
532 #ifdef HAVE_OPENSSL
533         if (!CC->redirect_ssl) CC->kill_me = 1;         /* kill session if no crypto */
534 #endif
535         imap_greeting();
536 }
537
538
539 /*
540  * implements the LOGIN command (ordinary username/password login)
541  */
542 void imap_login(int num_parms, char *parms[])
543 {
544         if (num_parms != 4) {
545                 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
546                 return;
547         }
548
549         if (CtdlLoginExistingUser(NULL, parms[2]) == login_ok) {
550                 if (CtdlTryPassword(parms[3]) == pass_ok) {
551                         cprintf("%s OK [", parms[0]);
552                         imap_output_capability_string();
553                         cprintf("] Hello, %s\r\n", CC->user.fullname);
554                         return;
555                 }
556         }
557
558         cprintf("%s BAD Login incorrect\r\n", parms[0]);
559 }
560
561
562 /*
563  * Implements the AUTHENTICATE command
564  */
565 void imap_authenticate(int num_parms, char *parms[])
566 {
567         char buf[SIZ];
568
569         if (num_parms != 3) {
570                 cprintf("%s BAD incorrect number of parameters\r\n",
571                         parms[0]);
572                 return;
573         }
574
575         if (CC->logged_in) {
576                 cprintf("%s BAD Already logged in.\r\n", parms[0]);
577                 return;
578         }
579
580         if (!strcasecmp(parms[2], "LOGIN")) {
581                 CtdlEncodeBase64(buf, "Username:", 9, 0);
582                 cprintf("+ %s\r\n", buf);
583                 IMAP->authstate = imap_as_expecting_username;
584                 strcpy(IMAP->authseq, parms[0]);
585                 return;
586         }
587
588         if (!strcasecmp(parms[2], "PLAIN")) {
589                 // CtdlEncodeBase64(buf, "Username:", 9, 0);
590                 // cprintf("+ %s\r\n", buf);
591                 cprintf("+ \r\n");
592                 IMAP->authstate = imap_as_expecting_plainauth;
593                 strcpy(IMAP->authseq, parms[0]);
594                 return;
595         }
596
597         else {
598                 cprintf("%s NO AUTHENTICATE %s failed\r\n",
599                         parms[0], parms[1]);
600         }
601 }
602
603
604 void imap_auth_plain(char *cmd)
605 {
606         char decoded_authstring[1024];
607         char ident[256];
608         char user[256];
609         char pass[256];
610         int result;
611
612         memset(pass, 0, sizeof(pass));
613         CtdlDecodeBase64(decoded_authstring, cmd, strlen(cmd));
614         safestrncpy(ident, decoded_authstring, sizeof ident);
615         safestrncpy(user, &decoded_authstring[strlen(ident) + 1], sizeof user);
616         safestrncpy(pass, &decoded_authstring[strlen(ident) + strlen(user) + 2], sizeof pass);
617
618         IMAP->authstate = imap_as_normal;
619
620         if (!IsEmptyStr(ident)) {
621                 result = CtdlLoginExistingUser(user, ident);
622         }
623         else {
624                 result = CtdlLoginExistingUser(NULL, user);
625         }
626
627         if (result == login_ok) {
628                 if (CtdlTryPassword(pass) == pass_ok) {
629                         cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
630                         return;
631                 }
632         }
633         cprintf("%s NO authentication failed\r\n", IMAP->authseq);
634 }
635
636
637 void imap_auth_login_user(char *cmd)
638 {
639         char buf[SIZ];
640
641         CtdlDecodeBase64(buf, cmd, SIZ);
642         CtdlLoginExistingUser(NULL, buf);
643         CtdlEncodeBase64(buf, "Password:", 9, 0);
644         cprintf("+ %s\r\n", buf);
645         IMAP->authstate = imap_as_expecting_password;
646         return;
647 }
648
649
650 void imap_auth_login_pass(char *cmd)
651 {
652         char buf[SIZ];
653
654         memset(buf, 0, sizeof(buf));
655         CtdlDecodeBase64(buf, cmd, SIZ);
656         if (CtdlTryPassword(buf) == pass_ok) {
657                 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
658         } else {
659                 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
660         }
661         IMAP->authstate = imap_as_normal;
662         return;
663 }
664
665
666 /*
667  * implements the STARTTLS command (Citadel API version)
668  */
669 void imap_starttls(int num_parms, char *parms[])
670 {
671         char ok_response[SIZ];
672         char nosup_response[SIZ];
673         char error_response[SIZ];
674
675         sprintf(ok_response,    "%s OK begin TLS negotiation now\r\n",  parms[0]);
676         sprintf(nosup_response, "%s NO TLS not supported here\r\n",     parms[0]);
677         sprintf(error_response, "%s BAD Internal error\r\n",            parms[0]);
678         CtdlModuleStartCryptoMsgs(ok_response, nosup_response, error_response);
679 }
680
681
682 /*
683  * implements the SELECT command
684  */
685 void imap_select(int num_parms, char *parms[])
686 {
687         char towhere[SIZ];
688         char augmented_roomname[ROOMNAMELEN];
689         int c = 0;
690         int ok = 0;
691         int ra = 0;
692         struct ctdlroom QRscratch;
693         int msgs, new;
694         int floornum;
695         int roomflags;
696         int i;
697
698         /* Convert the supplied folder name to a roomname */
699         i = imap_roomname(towhere, sizeof towhere, parms[2]);
700         if (i < 0) {
701                 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
702                 IMAP->selected = 0;
703                 return;
704         }
705         floornum = (i & 0x00ff);
706         roomflags = (i & 0xff00);
707
708         /* First try a regular match */
709         c = CtdlGetRoom(&QRscratch, towhere);
710
711         /* Then try a mailbox name match */
712         if (c != 0) {
713                 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname, &CC->user, towhere);
714                 c = CtdlGetRoom(&QRscratch, augmented_roomname);
715                 if (c == 0) {
716                         strcpy(towhere, augmented_roomname);
717                 }
718         }
719
720         /* If the room exists, check security/access */
721         if (c == 0) {
722                 /* See if there is an existing user/room relationship */
723                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
724
725                 /* normal clients have to pass through security */
726                 if (ra & UA_KNOWN) {
727                         ok = 1;
728                 }
729         }
730
731         /* Fail here if no such room */
732         if (!ok) {
733                 cprintf("%s NO ... no such room, or access denied\r\n", parms[0]);
734                 return;
735         }
736
737         /* If we already had some other folder selected, auto-expunge it */
738         imap_do_expunge();
739
740         /*
741          * CtdlUserGoto() formally takes us to the desired room, happily returning
742          * the number of messages and number of new messages.
743          */
744         memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
745         CtdlUserGoto(NULL, 0, 0, &msgs, &new);
746         IMAP->selected = 1;
747
748         if (!strcasecmp(parms[1], "EXAMINE")) {
749                 IMAP->readonly = 1;
750         } else {
751                 IMAP->readonly = 0;
752         }
753
754         imap_load_msgids();
755         IMAP->last_mtime = CC->room.QRmtime;
756
757         cprintf("* %d EXISTS\r\n", msgs);
758         cprintf("* %d RECENT\r\n", new);
759
760         cprintf("* OK [UIDVALIDITY %ld] UID validity status\r\n", GLOBAL_UIDVALIDITY_VALUE);
761         cprintf("* OK [UIDNEXT %ld] Predicted next UID\r\n", CitControl.MMhighest + 1);
762
763         /* Technically, \Deleted is a valid flag, but not a permanent flag,
764          * because we don't maintain its state across sessions.  Citadel
765          * automatically expunges mailboxes when they are de-selected.
766          * 
767          * Unfortunately, omitting \Deleted as a PERMANENTFLAGS flag causes
768          * some clients (particularly Thunderbird) to misbehave -- they simply
769          * elect not to transmit the flag at all.  So we have to advertise
770          * \Deleted as a PERMANENTFLAGS flag, even though it technically isn't.
771          */
772         cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
773         cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen \\Answered)] permanent flags\r\n");
774
775         cprintf("%s OK [%s] %s completed\r\n",
776                 parms[0],
777                 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"), parms[1]
778         );
779 }
780
781
782 /*
783  * Does the real work for expunge.
784  */
785 int imap_do_expunge(void)
786 {
787         int i;
788         int num_expunged = 0;
789         long *delmsgs = NULL;
790         int num_delmsgs = 0;
791
792         CtdlLogPrintf(CTDL_DEBUG, "imap_do_expunge() called\n");
793         if (IMAP->selected == 0) {
794                 return (0);
795         }
796
797         if (IMAP->num_msgs > 0) {
798                 delmsgs = malloc(IMAP->num_msgs * sizeof(long));
799                 for (i = 0; i < IMAP->num_msgs; ++i) {
800                         if (IMAP->flags[i] & IMAP_DELETED) {
801                                 delmsgs[num_delmsgs++] = IMAP->msgids[i];
802                         }
803                 }
804                 if (num_delmsgs > 0) {
805                         CtdlDeleteMessages(CC->room.QRname, delmsgs, num_delmsgs, "");
806                 }
807                 num_expunged += num_delmsgs;
808                 free(delmsgs);
809         }
810
811         if (num_expunged > 0) {
812                 imap_rescan_msgids();
813         }
814
815         CtdlLogPrintf(CTDL_DEBUG, "Expunged %d messages from <%s>\n", num_expunged, CC->room.QRname);
816         return (num_expunged);
817 }
818
819
820 /*
821  * implements the EXPUNGE command syntax
822  */
823 void imap_expunge(int num_parms, char *parms[])
824 {
825         int num_expunged = 0;
826
827         num_expunged = imap_do_expunge();
828         cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
829 }
830
831
832 /*
833  * implements the CLOSE command
834  */
835 void imap_close(int num_parms, char *parms[])
836 {
837
838         /* Yes, we always expunge on close. */
839         if (IMAP->selected) {
840                 imap_do_expunge();
841         }
842
843         IMAP->selected = 0;
844         IMAP->readonly = 0;
845         imap_free_msgids();
846         cprintf("%s OK CLOSE completed\r\n", parms[0]);
847 }
848
849
850 /*
851  * Implements the NAMESPACE command.
852  */
853 void imap_namespace(int num_parms, char *parms[])
854 {
855         int i;
856         struct floor *fl;
857         int floors = 0;
858         char buf[SIZ];
859
860         cprintf("* NAMESPACE ");
861
862         /* All personal folders are subordinate to INBOX. */
863         cprintf("((\"INBOX/\" \"/\")) ");
864
865         /* Other users' folders ... coming soon! FIXME */
866         cprintf("NIL ");
867
868         /* Show all floors as shared namespaces.  Neato! */
869         cprintf("(");
870         for (i = 0; i < MAXFLOORS; ++i) {
871                 fl = CtdlGetCachedFloor(i);
872                 if (fl->f_flags & F_INUSE) {
873                         if (floors > 0) cprintf(" ");
874                         cprintf("(");
875                         sprintf(buf, "%s/", fl->f_name);
876                         imap_strout(buf);
877                         cprintf(" \"/\")");
878                         ++floors;
879                 }
880         }
881         cprintf(")");
882
883         /* Wind it up with a newline and a completion message. */
884         cprintf("\r\n");
885         cprintf("%s OK NAMESPACE completed\r\n", parms[0]);
886 }
887
888
889 /*
890  * Implements the CREATE command
891  *
892  */
893 void imap_create(int num_parms, char *parms[])
894 {
895         int ret;
896         char roomname[ROOMNAMELEN];
897         int floornum;
898         int flags;
899         int newroomtype = 0;
900         int newroomview = 0;
901         char *notification_message = NULL;
902
903         if (num_parms < 3) {
904                 cprintf("%s NO A foder name must be specified\r\n", parms[0]);
905                 return;
906         }
907
908         if (strchr(parms[2], '\\') != NULL) {
909                 cprintf("%s NO Invalid character in folder name\r\n", parms[0]);
910                 CtdlLogPrintf(CTDL_DEBUG, "invalid character in folder name\n");
911                 return;
912         }
913
914         ret = imap_roomname(roomname, sizeof roomname, parms[2]);
915         if (ret < 0) {
916                 cprintf("%s NO Invalid mailbox name or location\r\n",
917                         parms[0]);
918                 CtdlLogPrintf(CTDL_DEBUG, "invalid mailbox name or location\n");
919                 return;
920         }
921         floornum = (ret & 0x00ff);      /* lower 8 bits = floor number */
922         flags = (ret & 0xff00); /* upper 8 bits = flags        */
923
924         if (flags & IR_MAILBOX) {
925                 if (strncasecmp(parms[2], "INBOX/", 6)) {
926                         cprintf("%s NO Personal folders must be created under INBOX\r\n", parms[0]);
927                         CtdlLogPrintf(CTDL_DEBUG, "not subordinate to inbox\n");
928                         return;
929                 }
930         }
931
932         if (flags & IR_MAILBOX) {
933                 newroomtype = 4;                /* private mailbox */
934                 newroomview = VIEW_MAILBOX;
935         } else {
936                 newroomtype = 0;                /* public folder */
937                 newroomview = VIEW_BBS;
938         }
939
940         CtdlLogPrintf(CTDL_INFO, "Create new room <%s> on floor <%d> with type <%d>\n",
941                 roomname, floornum, newroomtype);
942
943         ret = CtdlCreateRoom(roomname, newroomtype, "", floornum, 1, 0, newroomview);
944         if (ret == 0) {
945                 /*** DO NOT CHANGE THIS ERROR MESSAGE IN ANY WAY!  BYNARI CONNECTOR DEPENDS ON IT! ***/
946                 cprintf("%s NO Mailbox already exists, or create failed\r\n", parms[0]);
947         } else {
948                 cprintf("%s OK CREATE completed\r\n", parms[0]);
949                 /* post a message in Aide> describing the new room */
950                 notification_message = malloc(1024);
951                 snprintf(notification_message, 1024,
952                         "A new room called \"%s\" has been created by %s%s%s%s\n",
953                         roomname,
954                         CC->user.fullname,
955                         ((ret & QR_MAILBOX) ? " [personal]" : ""),
956                         ((ret & QR_PRIVATE) ? " [private]" : ""),
957                         ((ret & QR_GUESSNAME) ? " [hidden]" : "")
958                 );
959                 CtdlAideMessage(notification_message, "Room Creation Message");
960                 free(notification_message);
961         }
962         CtdlLogPrintf(CTDL_DEBUG, "imap_create() completed\n");
963 }
964
965
966 /*
967  * Locate a room by its IMAP folder name, and check access to it.
968  * If zapped_ok is nonzero, we can also look for the room in the zapped list.
969  */
970 int imap_grabroom(char *returned_roomname, char *foldername, int zapped_ok)
971 {
972         int ret;
973         char augmented_roomname[ROOMNAMELEN];
974         char roomname[ROOMNAMELEN];
975         int c;
976         struct ctdlroom QRscratch;
977         int ra;
978         int ok = 0;
979
980         ret = imap_roomname(roomname, sizeof roomname, foldername);
981         if (ret < 0) {
982                 return (1);
983         }
984
985         /* First try a regular match */
986         c = CtdlGetRoom(&QRscratch, roomname);
987
988         /* Then try a mailbox name match */
989         if (c != 0) {
990                 CtdlMailboxName(augmented_roomname, sizeof augmented_roomname,
991                             &CC->user, roomname);
992                 c = CtdlGetRoom(&QRscratch, augmented_roomname);
993                 if (c == 0)
994                         strcpy(roomname, augmented_roomname);
995         }
996
997         /* If the room exists, check security/access */
998         if (c == 0) {
999                 /* See if there is an existing user/room relationship */
1000                 CtdlRoomAccess(&QRscratch, &CC->user, &ra, NULL);
1001
1002                 /* normal clients have to pass through security */
1003                 if (ra & UA_KNOWN) {
1004                         ok = 1;
1005                 }
1006                 if ((zapped_ok) && (ra & UA_ZAPPED)) {
1007                         ok = 1;
1008                 }
1009         }
1010
1011         /* Fail here if no such room */
1012         if (!ok) {
1013                 strcpy(returned_roomname, "");
1014                 return (2);
1015         } else {
1016                 strcpy(returned_roomname, QRscratch.QRname);
1017                 return (0);
1018         }
1019 }
1020
1021
1022 /*
1023  * Implements the STATUS command (sort of)
1024  *
1025  */
1026 void imap_status(int num_parms, char *parms[])
1027 {
1028         int ret;
1029         char roomname[ROOMNAMELEN];
1030         char buf[SIZ];
1031         char savedroom[ROOMNAMELEN];
1032         int msgs, new;
1033
1034         ret = imap_grabroom(roomname, parms[2], 1);
1035         if (ret != 0) {
1036                 cprintf
1037                     ("%s NO Invalid mailbox name or location, or access denied\r\n",
1038                      parms[0]);
1039                 return;
1040         }
1041
1042         /*
1043          * CtdlUserGoto() formally takes us to the desired room, happily returning
1044          * the number of messages and number of new messages.  (If another
1045          * folder is selected, save its name so we can return there!!!!!)
1046          */
1047         if (IMAP->selected) {
1048                 strcpy(savedroom, CC->room.QRname);
1049         }
1050         CtdlUserGoto(roomname, 0, 0, &msgs, &new);
1051
1052         /*
1053          * Tell the client what it wants to know.  In fact, tell it *more* than
1054          * it wants to know.  We happily IGnore the supplied status data item
1055          * names and simply spew all possible data items.  It's far easier to
1056          * code and probably saves us some processing time too.
1057          */
1058         imap_mailboxname(buf, sizeof buf, &CC->room);
1059         cprintf("* STATUS ");
1060         imap_strout(buf);
1061         cprintf(" (MESSAGES %d ", msgs);
1062         cprintf("RECENT %d ", new);     /* Initially, new==recent */
1063         cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
1064         cprintf("UNSEEN %d)\r\n", new);
1065
1066         /*
1067          * If another folder is selected, go back to that room so we can resume
1068          * our happy day without violent explosions.
1069          */
1070         if (IMAP->selected) {
1071                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new);
1072         }
1073
1074         /*
1075          * Oooh, look, we're done!
1076          */
1077         cprintf("%s OK STATUS completed\r\n", parms[0]);
1078 }
1079
1080
1081 /*
1082  * Implements the SUBSCRIBE command
1083  *
1084  */
1085 void imap_subscribe(int num_parms, char *parms[])
1086 {
1087         int ret;
1088         char roomname[ROOMNAMELEN];
1089         char savedroom[ROOMNAMELEN];
1090         int msgs, new;
1091
1092         ret = imap_grabroom(roomname, parms[2], 1);
1093         if (ret != 0) {
1094                 cprintf(
1095                         "%s NO Error %d: invalid mailbox name or location, or access denied\r\n",
1096                         parms[0],
1097                         ret
1098                 );
1099                 return;
1100         }
1101
1102         /*
1103          * CtdlUserGoto() formally takes us to the desired room, which has the side
1104          * effect of marking the room as not-zapped ... exactly the effect
1105          * we're looking for.
1106          */
1107         if (IMAP->selected) {
1108                 strcpy(savedroom, CC->room.QRname);
1109         }
1110         CtdlUserGoto(roomname, 0, 0, &msgs, &new);
1111
1112         /*
1113          * If another folder is selected, go back to that room so we can resume
1114          * our happy day without violent explosions.
1115          */
1116         if (IMAP->selected) {
1117                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new);
1118         }
1119
1120         cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
1121 }
1122
1123
1124 /*
1125  * Implements the UNSUBSCRIBE command
1126  *
1127  */
1128 void imap_unsubscribe(int num_parms, char *parms[])
1129 {
1130         int ret;
1131         char roomname[ROOMNAMELEN];
1132         char savedroom[ROOMNAMELEN];
1133         int msgs, new;
1134
1135         ret = imap_grabroom(roomname, parms[2], 1);
1136         if (ret != 0) {
1137                 cprintf
1138                     ("%s NO Invalid mailbox name or location, or access denied\r\n",
1139                      parms[0]);
1140                 return;
1141         }
1142
1143         /*
1144          * CtdlUserGoto() formally takes us to the desired room.
1145          */
1146         if (IMAP->selected) {
1147                 strcpy(savedroom, CC->room.QRname);
1148         }
1149         CtdlUserGoto(roomname, 0, 0, &msgs, &new);
1150
1151         /* 
1152          * Now make the API call to zap the room
1153          */
1154         if (CtdlForgetThisRoom() == 0) {
1155                 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
1156         } else {
1157                 cprintf
1158                     ("%s NO You may not unsubscribe from this folder.\r\n",
1159                      parms[0]);
1160         }
1161
1162         /*
1163          * If another folder is selected, go back to that room so we can resume
1164          * our happy day without violent explosions.
1165          */
1166         if (IMAP->selected) {
1167                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new);
1168         }
1169 }
1170
1171
1172 /*
1173  * Implements the DELETE command
1174  *
1175  */
1176 void imap_delete(int num_parms, char *parms[])
1177 {
1178         int ret;
1179         char roomname[ROOMNAMELEN];
1180         char savedroom[ROOMNAMELEN];
1181         int msgs, new;
1182
1183         ret = imap_grabroom(roomname, parms[2], 1);
1184         if (ret != 0) {
1185                 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
1186                         parms[0]);
1187                 return;
1188         }
1189
1190         /*
1191          * CtdlUserGoto() formally takes us to the desired room, happily returning
1192          * the number of messages and number of new messages.  (If another
1193          * folder is selected, save its name so we can return there!!!!!)
1194          */
1195         if (IMAP->selected) {
1196                 strcpy(savedroom, CC->room.QRname);
1197         }
1198         CtdlUserGoto(roomname, 0, 0, &msgs, &new);
1199
1200         /*
1201          * Now delete the room.
1202          */
1203         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1204                 CtdlScheduleRoomForDeletion(&CC->room);
1205                 cprintf("%s OK DELETE completed\r\n", parms[0]);
1206         } else {
1207                 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1208         }
1209
1210         /*
1211          * If another folder is selected, go back to that room so we can resume
1212          * our happy day without violent explosions.
1213          */
1214         if (IMAP->selected) {
1215                 CtdlUserGoto(savedroom, 0, 0, &msgs, &new);
1216         }
1217 }
1218
1219
1220 /*
1221  * Back end function for imap_rename()
1222  */
1223 void imap_rename_backend(struct ctdlroom *qrbuf, void *data)
1224 {
1225         char foldername[SIZ];
1226         char newfoldername[SIZ];
1227         char newroomname[ROOMNAMELEN];
1228         int newfloor = 0;
1229         struct irl *irlp = NULL;        /* scratch pointer */
1230         struct irlparms *irlparms;
1231
1232         irlparms = (struct irlparms *) data;
1233         imap_mailboxname(foldername, sizeof foldername, qrbuf);
1234
1235         /* Rename subfolders */
1236         if ((!strncasecmp(foldername, irlparms->oldname,
1237                           strlen(irlparms->oldname))
1238              && (foldername[strlen(irlparms->oldname)] == '/'))) {
1239
1240                 sprintf(newfoldername, "%s/%s",
1241                         irlparms->newname,
1242                         &foldername[strlen(irlparms->oldname) + 1]
1243                     );
1244
1245                 newfloor = imap_roomname(newroomname,
1246                                          sizeof newroomname,
1247                                          newfoldername) & 0xFF;
1248
1249                 irlp = (struct irl *) malloc(sizeof(struct irl));
1250                 strcpy(irlp->irl_newroom, newroomname);
1251                 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1252                 irlp->irl_newfloor = newfloor;
1253                 irlp->next = *(irlparms->irl);
1254                 *(irlparms->irl) = irlp;
1255         }
1256 }
1257
1258
1259 /*
1260  * Implements the RENAME command
1261  *
1262  */
1263 void imap_rename(int num_parms, char *parms[])
1264 {
1265         char old_room[ROOMNAMELEN];
1266         char new_room[ROOMNAMELEN];
1267         int oldr, newr;
1268         int new_floor;
1269         int r;
1270         struct irl *irl = NULL; /* the list */
1271         struct irl *irlp = NULL;        /* scratch pointer */
1272         struct irlparms irlparms;
1273         char buf[1024];
1274
1275         if (strchr(parms[3], '\\') != NULL) {
1276                 cprintf("%s NO Invalid character in folder name\r\n",
1277                         parms[0]);
1278                 return;
1279         }
1280
1281         oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1282         newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1283         new_floor = (newr & 0xFF);
1284
1285         r = CtdlRenameRoom(old_room, new_room, new_floor);
1286
1287         if (r == crr_room_not_found) {
1288                 cprintf("%s NO Could not locate this folder\r\n",
1289                         parms[0]);
1290                 return;
1291         }
1292         if (r == crr_already_exists) {
1293                 cprintf("%s NO '%s' already exists.\r\n", parms[0], parms[2]);
1294                 return;
1295         }
1296         if (r == crr_noneditable) {
1297                 cprintf("%s NO This folder is not editable.\r\n", parms[0]);
1298                 return;
1299         }
1300         if (r == crr_invalid_floor) {
1301                 cprintf("%s NO Folder root does not exist.\r\n", parms[0]);
1302                 return;
1303         }
1304         if (r == crr_access_denied) {
1305                 cprintf("%s NO You do not have permission to edit this folder.\r\n",
1306                         parms[0]);
1307                 return;
1308         }
1309         if (r != crr_ok) {
1310                 cprintf("%s NO Rename failed - undefined error %d\r\n",
1311                         parms[0], r);
1312                 return;
1313         }
1314
1315         /* If this is the INBOX, then RFC2060 says we have to just move the
1316          * contents.  In a Citadel environment it's easier to rename the room
1317          * (already did that) and create a new inbox.
1318          */
1319         if (!strcasecmp(parms[2], "INBOX")) {
1320                 CtdlCreateRoom(MAILROOM, 4, "", 0, 1, 0, VIEW_MAILBOX);
1321         }
1322
1323         /* Otherwise, do the subfolders.  Build a list of rooms to rename... */
1324         else {
1325                 irlparms.oldname = parms[2];
1326                 irlparms.newname = parms[3];
1327                 irlparms.irl = &irl;
1328                 CtdlForEachRoom(imap_rename_backend, (void *) &irlparms);
1329
1330                 /* ... and now rename them. */
1331                 while (irl != NULL) {
1332                         r = CtdlRenameRoom(irl->irl_oldroom,
1333                                            irl->irl_newroom,
1334                                            irl->irl_newfloor);
1335                         if (r != crr_ok) {
1336                                 /* FIXME handle error returns better */
1337                                 CtdlLogPrintf(CTDL_ERR, "CtdlRenameRoom() error %d\n", r);
1338                         }
1339                         irlp = irl;
1340                         irl = irl->next;
1341                         free(irlp);
1342                 }
1343         }
1344
1345         snprintf(buf, sizeof buf, "IMAP folder \"%s\" renamed to \"%s\" by %s\n",
1346                 parms[2],
1347                 parms[3],
1348                 CC->curr_user
1349         );
1350         CtdlAideMessage(buf, "IMAP folder rename");
1351
1352         cprintf("%s OK RENAME completed\r\n", parms[0]);
1353 }
1354
1355
1356 /* 
1357  * Main command loop for IMAP sessions.
1358  */
1359 void imap_command_loop(void)
1360 {
1361         char cmdbuf[SIZ];
1362         char *parms[SIZ];
1363         int num_parms;
1364         struct timeval tv1, tv2;
1365         suseconds_t total_time = 0;
1366         int untagged_ok = 1;
1367
1368         gettimeofday(&tv1, NULL);
1369         CC->lastcmd = time(NULL);
1370         memset(cmdbuf, 0, sizeof cmdbuf);       /* Clear it, just in case */
1371         flush_output();
1372         if (client_getln(cmdbuf, sizeof cmdbuf) < 1) {
1373                 CtdlLogPrintf(CTDL_ERR, "Client disconnected: ending session.\r\n");
1374                 CC->kill_me = 1;
1375                 return;
1376         }
1377
1378         if (IMAP->authstate == imap_as_expecting_password) {
1379                 CtdlLogPrintf(CTDL_INFO, "IMAP: <password>\n");
1380         }
1381         else if (IMAP->authstate == imap_as_expecting_plainauth) {
1382                 CtdlLogPrintf(CTDL_INFO, "IMAP: <plain_auth>\n");
1383         }
1384         else if (bmstrcasestr(cmdbuf, " LOGIN ")) {
1385                 CtdlLogPrintf(CTDL_INFO, "IMAP: LOGIN...\n");
1386         }
1387         else {
1388                 CtdlLogPrintf(CTDL_INFO, "IMAP: %s\n", cmdbuf);
1389         }
1390
1391         while (strlen(cmdbuf) < 5)
1392                 strcat(cmdbuf, " ");
1393
1394         /* strip off l/t whitespace and CRLF */
1395         if (cmdbuf[strlen(cmdbuf) - 1] == '\n')
1396                 cmdbuf[strlen(cmdbuf) - 1] = 0;
1397         if (cmdbuf[strlen(cmdbuf) - 1] == '\r')
1398                 cmdbuf[strlen(cmdbuf) - 1] = 0;
1399         striplt(cmdbuf);
1400
1401         /* If we're in the middle of a multi-line command, handle that */
1402         if (IMAP->authstate == imap_as_expecting_username) {
1403                 imap_auth_login_user(cmdbuf);
1404                 return;
1405         }
1406         if (IMAP->authstate == imap_as_expecting_plainauth) {
1407                 imap_auth_plain(cmdbuf);
1408                 return;
1409         }
1410         if (IMAP->authstate == imap_as_expecting_password) {
1411                 imap_auth_login_pass(cmdbuf);
1412                 return;
1413         }
1414
1415         /* Ok, at this point we're in normal command mode.
1416          * If the command just submitted does not contain a literal, we
1417          * might think about delivering some untagged stuff...
1418          */
1419         if (cmdbuf[strlen(cmdbuf)-1] == '}') {
1420                 untagged_ok = 0;
1421         }
1422
1423         /* Grab the tag, command, and parameters. */
1424         num_parms = imap_parameterize(parms, cmdbuf);
1425
1426         /* RFC3501 says that we cannot output untagged data during these commands */
1427         if (num_parms >= 2) {
1428                 if (  (!strcasecmp(parms[1], "FETCH"))
1429                    || (!strcasecmp(parms[1], "STORE"))
1430                    || (!strcasecmp(parms[1], "SEARCH"))
1431                 ) {
1432                         untagged_ok = 0;
1433                 }
1434         }
1435         
1436         if (untagged_ok) {
1437
1438                 /* we can put any additional untagged stuff right here in the future */
1439
1440                 /*
1441                  * Before processing the command that was just entered... if we happen
1442                  * to have a folder selected, we'd like to rescan that folder for new
1443                  * messages, and for deletions/changes of existing messages.  This
1444                  * could probably be optimized better with some deep thought...
1445                  */
1446                 if (IMAP->selected) {
1447                         imap_rescan_msgids();
1448                 }
1449         }
1450
1451         /* Now for the command set. */
1452
1453         if (num_parms < 2) {
1454                 cprintf("BAD syntax error\r\n");
1455         }
1456
1457         /* The commands below may be executed in any state */
1458
1459         else if ((!strcasecmp(parms[1], "NOOP"))
1460                  || (!strcasecmp(parms[1], "CHECK"))) {
1461                 cprintf("%s OK No operation\r\n",
1462                         parms[0]);
1463         }
1464
1465         else if (!strcasecmp(parms[1], "ID")) {
1466                 imap_id(num_parms, parms);
1467         }
1468
1469
1470         else if (!strcasecmp(parms[1], "LOGOUT")) {
1471                 if (IMAP->selected) {
1472                         imap_do_expunge();      /* yes, we auto-expunge at logout */
1473                 }
1474                 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1475                 cprintf("%s OK Citadel IMAP session ended.\r\n",
1476                         parms[0]);
1477                 CC->kill_me = 1;
1478                 return;
1479         }
1480
1481         else if (!strcasecmp(parms[1], "LOGIN")) {
1482                 imap_login(num_parms, parms);
1483         }
1484
1485         else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1486                 imap_authenticate(num_parms, parms);
1487         }
1488
1489         else if (!strcasecmp(parms[1], "CAPABILITY")) {
1490                 imap_capability(num_parms, parms);
1491         }
1492 #ifdef HAVE_OPENSSL
1493         else if (!strcasecmp(parms[1], "STARTTLS")) {
1494                 imap_starttls(num_parms, parms);
1495         }
1496 #endif
1497         else if (!CC->logged_in) {
1498                 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1499         }
1500
1501         /* The commans below require a logged-in state */
1502
1503         else if (!strcasecmp(parms[1], "SELECT")) {
1504                 imap_select(num_parms, parms);
1505         }
1506
1507         else if (!strcasecmp(parms[1], "EXAMINE")) {
1508                 imap_select(num_parms, parms);
1509         }
1510
1511         else if (!strcasecmp(parms[1], "LSUB")) {
1512                 imap_list(num_parms, parms);
1513         }
1514
1515         else if (!strcasecmp(parms[1], "LIST")) {
1516                 imap_list(num_parms, parms);
1517         }
1518
1519         else if (!strcasecmp(parms[1], "CREATE")) {
1520                 imap_create(num_parms, parms);
1521         }
1522
1523         else if (!strcasecmp(parms[1], "DELETE")) {
1524                 imap_delete(num_parms, parms);
1525         }
1526
1527         else if (!strcasecmp(parms[1], "RENAME")) {
1528                 imap_rename(num_parms, parms);
1529         }
1530
1531         else if (!strcasecmp(parms[1], "STATUS")) {
1532                 imap_status(num_parms, parms);
1533         }
1534
1535         else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1536                 imap_subscribe(num_parms, parms);
1537         }
1538
1539         else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1540                 imap_unsubscribe(num_parms, parms);
1541         }
1542
1543         else if (!strcasecmp(parms[1], "APPEND")) {
1544                 imap_append(num_parms, parms);
1545         }
1546
1547         else if (!strcasecmp(parms[1], "NAMESPACE")) {
1548                 imap_namespace(num_parms, parms);
1549         }
1550
1551         else if (!strcasecmp(parms[1], "SETACL")) {
1552                 imap_setacl(num_parms, parms);
1553         }
1554
1555         else if (!strcasecmp(parms[1], "DELETEACL")) {
1556                 imap_deleteacl(num_parms, parms);
1557         }
1558
1559         else if (!strcasecmp(parms[1], "GETACL")) {
1560                 imap_getacl(num_parms, parms);
1561         }
1562
1563         else if (!strcasecmp(parms[1], "LISTRIGHTS")) {
1564                 imap_listrights(num_parms, parms);
1565         }
1566
1567         else if (!strcasecmp(parms[1], "MYRIGHTS")) {
1568                 imap_myrights(num_parms, parms);
1569         }
1570
1571         else if (!strcasecmp(parms[1], "GETMETADATA")) {
1572                 imap_getmetadata(num_parms, parms);
1573         }
1574
1575         else if (!strcasecmp(parms[1], "SETMETADATA")) {
1576                 imap_setmetadata(num_parms, parms);
1577         }
1578
1579         else if (IMAP->selected == 0) {
1580                 cprintf("%s BAD no folder selected\r\n", parms[0]);
1581         }
1582
1583         /* The commands below require the SELECT state on a mailbox */
1584
1585         else if (!strcasecmp(parms[1], "FETCH")) {
1586                 imap_fetch(num_parms, parms);
1587         }
1588
1589         else if ((!strcasecmp(parms[1], "UID"))
1590                  && (!strcasecmp(parms[2], "FETCH"))) {
1591                 imap_uidfetch(num_parms, parms);
1592         }
1593
1594         else if (!strcasecmp(parms[1], "SEARCH")) {
1595                 imap_search(num_parms, parms);
1596         }
1597
1598         else if ((!strcasecmp(parms[1], "UID"))
1599                  && (!strcasecmp(parms[2], "SEARCH"))) {
1600                 imap_uidsearch(num_parms, parms);
1601         }
1602
1603         else if (!strcasecmp(parms[1], "STORE")) {
1604                 imap_store(num_parms, parms);
1605         }
1606
1607         else if ((!strcasecmp(parms[1], "UID"))
1608                  && (!strcasecmp(parms[2], "STORE"))) {
1609                 imap_uidstore(num_parms, parms);
1610         }
1611
1612         else if (!strcasecmp(parms[1], "COPY")) {
1613                 imap_copy(num_parms, parms);
1614         }
1615
1616         else if ((!strcasecmp(parms[1], "UID")) && (!strcasecmp(parms[2], "COPY"))) {
1617                 imap_uidcopy(num_parms, parms);
1618         }
1619
1620         else if (!strcasecmp(parms[1], "EXPUNGE")) {
1621                 imap_expunge(num_parms, parms);
1622         }
1623
1624         else if ((!strcasecmp(parms[1], "UID")) && (!strcasecmp(parms[2], "EXPUNGE"))) {
1625                 imap_expunge(num_parms, parms);
1626         }
1627
1628         else if (!strcasecmp(parms[1], "CLOSE")) {
1629                 imap_close(num_parms, parms);
1630         }
1631
1632         /* End of commands.  If we get here, the command is either invalid
1633          * or unimplemented.
1634          */
1635
1636         else {
1637                 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1638         }
1639
1640         /* If the client transmitted a message we can free it now */
1641         imap_free_transmitted_message();
1642
1643         gettimeofday(&tv2, NULL);
1644         total_time = (tv2.tv_usec + (tv2.tv_sec * 1000000)) - (tv1.tv_usec + (tv1.tv_sec * 1000000));
1645         CtdlLogPrintf(CTDL_DEBUG, "IMAP command completed in %ld.%ld seconds\n",
1646                 (total_time / 1000000),
1647                 (total_time % 1000000)
1648         );
1649 }
1650
1651
1652 const char *CitadelServiceIMAP="IMAP";
1653 const char *CitadelServiceIMAPS="IMAPS";
1654
1655 /*
1656  * This function is called to register the IMAP extension with Citadel.
1657  */
1658 CTDL_MODULE_INIT(imap)
1659 {
1660         if (!threading)
1661         {
1662                 CtdlRegisterServiceHook(config.c_imap_port,
1663                                         NULL, imap_greeting, imap_command_loop, NULL, CitadelServiceIMAP);
1664 #ifdef HAVE_OPENSSL
1665                 CtdlRegisterServiceHook(config.c_imaps_port,
1666                                         NULL, imaps_greeting, imap_command_loop, NULL, CitadelServiceIMAPS);
1667 #endif
1668                 CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1669         }
1670         
1671         /* return our Subversion id for the Log */
1672         return "$Id$";
1673 }