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