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