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