* Removed PLAIN because there are two different ways to execute the
[citadel.git] / citadel / serv_imap.c
1 /*
2  * $Id$ 
3  *
4  * IMAP server for the Citadel/UX system
5  * Copyright (C) 2000-2002 by Art Cancro and others.
6  * This code is released under the terms of the GNU General Public License.
7  *
8  * WARNING: Mark Crispin is an idiot.  IMAP is the most brain-damaged protocol
9  * you will ever have the profound lack of pleasure to encounter.
10  */
11
12 #include "sysdep.h"
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <stdio.h>
16 #include <fcntl.h>
17 #include <signal.h>
18 #include <pwd.h>
19 #include <errno.h>
20 #include <sys/types.h>
21
22 #if TIME_WITH_SYS_TIME
23 # include <sys/time.h>
24 # include <time.h>
25 #else
26 # if HAVE_SYS_TIME_H
27 #  include <sys/time.h>
28 # else
29 #  include <time.h>
30 # endif
31 #endif
32
33 #include <sys/wait.h>
34 #include <ctype.h>
35 #include <string.h>
36 #include <limits.h>
37
38 #ifdef HAVE_OPENSSL_XXX /* temporarily disabled due to bugs */
39 #include <openssl/ssl.h>
40 #include <openssl/err.h>
41 #include <openssl/rand.h>
42 #endif
43
44 #include "citadel.h"
45 #include "server.h"
46 #include "sysdep_decls.h"
47 #include "citserver.h"
48 #include "support.h"
49 #include "config.h"
50 #include "serv_extensions.h"
51 #include "room_ops.h"
52 #include "user_ops.h"
53 #include "policy.h"
54 #include "database.h"
55 #include "msgbase.h"
56 #include "tools.h"
57 #include "internet_addressing.h"
58 #include "serv_imap.h"
59 #include "imap_tools.h"
60 #include "imap_fetch.h"
61 #include "imap_search.h"
62 #include "imap_store.h"
63 #include "imap_misc.h"
64
65 #ifdef HAVE_OPENSSL_XXX /* temporarily disabled due to bugs */
66 #include "serv_crypto.h"
67 #endif
68
69 /* imap_rename() uses this struct containing list of rooms to rename */
70 struct irl {
71         struct irl *next;
72         char irl_oldroom[ROOMNAMELEN];
73         char irl_newroom[ROOMNAMELEN];
74         int irl_newfloor;
75 };
76
77 /* Data which is passed between imap_rename() and imap_rename_backend() */
78 struct irlparms { 
79         char *oldname;
80         char *newname;
81         struct irl **irl;
82 };
83
84
85 /*
86  * If there is a message ID map in memory, free it
87  */
88 void imap_free_msgids(void) {
89         if (IMAP->msgids != NULL) {
90                 phree(IMAP->msgids);
91                 IMAP->msgids = NULL;
92                 IMAP->num_msgs = 0;
93         }
94         if (IMAP->flags != NULL) {
95                 phree(IMAP->flags);
96                 IMAP->flags = NULL;
97         }
98 }
99
100
101 /*
102  * If there is a transmitted message in memory, free it
103  */
104 void imap_free_transmitted_message(void) {
105         if (IMAP->transmitted_message != NULL) {
106                 phree(IMAP->transmitted_message);
107                 IMAP->transmitted_message = NULL;
108                 IMAP->transmitted_length = 0;
109         }
110 }
111
112
113 /*
114  * Set the \\Seen flag for messages which aren't new
115  */
116 void imap_set_seen_flags(void) {
117         struct visit vbuf;
118         int i;
119
120         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
121         if (IMAP->num_msgs > 0) {
122                 for (i=0; i<IMAP->num_msgs; ++i) {
123                         if (is_msg_in_mset(vbuf.v_seen, IMAP->msgids[i])) {
124                                 IMAP->flags[i] |= IMAP_SEEN;
125                         }
126                         if (is_msg_in_mset(vbuf.v_answered, IMAP->msgids[i])) {
127                                 IMAP->flags[i] |= IMAP_ANSWERED;
128                         }
129                 }
130         }
131 }
132
133
134
135
136 /*
137  * Back end for imap_load_msgids()
138  *
139  * Optimization: instead of calling realloc() to add each message, we
140  * allocate space in the list for REALLOC_INCREMENT messages at a time.  This
141  * allows the mapping to proceed much faster.
142  */
143 void imap_add_single_msgid(long msgnum, void *userdata) {
144         
145         IMAP->num_msgs = IMAP->num_msgs + 1;
146         if (IMAP->msgids == NULL) {
147                 IMAP->msgids = mallok(IMAP->num_msgs * sizeof(long)
148                                         * REALLOC_INCREMENT);
149         }
150         else if (IMAP->num_msgs % REALLOC_INCREMENT == 0) {
151                 IMAP->msgids = reallok(IMAP->msgids,
152                         (IMAP->num_msgs + REALLOC_INCREMENT) * sizeof(long));
153         }
154         if (IMAP->flags == NULL) {
155                 IMAP->flags = mallok(IMAP->num_msgs * sizeof(long)
156                                         * REALLOC_INCREMENT);
157         }
158         else if (IMAP->num_msgs % REALLOC_INCREMENT == 0) {
159                 IMAP->flags = reallok(IMAP->flags,
160                         (IMAP->num_msgs + REALLOC_INCREMENT) * sizeof(long));
161         }
162         IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
163         IMAP->flags[IMAP->num_msgs - 1] = 0;
164 }
165
166
167
168 /*
169  * Set up a message ID map for the current room (folder)
170  */
171 void imap_load_msgids(void) {
172          
173         if (IMAP->selected == 0) {
174                 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
175                 return;
176         }
177
178         imap_free_msgids();     /* If there was already a map, free it */
179
180         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
181                 imap_add_single_msgid, NULL);
182
183         imap_set_seen_flags();
184         lprintf(9, "imap_load_msgids() mapped %d messages\n", IMAP->num_msgs);
185 }
186
187
188 /*
189  * Re-scan the selected room (folder) and see if it's been changed at all
190  */
191 void imap_rescan_msgids(void) {
192
193         int original_num_msgs = 0;
194         long original_highest = 0L;
195         int i, j;
196         int message_still_exists;
197         struct cdbdata *cdbfr;
198         long *msglist = NULL;
199         int num_msgs = 0;
200
201
202         if (IMAP->selected == 0) {
203                 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
204                 return;
205         }
206
207         /* Load the *current* message list from disk, so we can compare it
208          * to what we have in memory.
209          */
210         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
211         if (cdbfr != NULL) {
212                 msglist = mallok(cdbfr->len);
213                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
214                 num_msgs = cdbfr->len / sizeof(long);
215                 cdb_free(cdbfr);
216         }
217         else {
218                 num_msgs = 0;
219         }
220
221         /*
222          * Check to see if any of the messages we know about have been expunged
223          */
224         if (IMAP->num_msgs > 0)
225          for (i=0; i<IMAP->num_msgs; ++i) {
226
227                 message_still_exists = 0;
228                 if (num_msgs > 0) for (j = 0; j < num_msgs; ++j) {
229                         if (msglist[j] == IMAP->msgids[i]) {
230                                 message_still_exists = 1;
231                         }
232                 }
233
234                 if (message_still_exists == 0) {
235                         cprintf("* %d EXPUNGE\r\n", i+1);
236
237                         /* Here's some nice stupid nonsense.  When a message
238                          * is expunged, we have to slide all the existing
239                          * messages up in the message array.
240                          */
241                         --IMAP->num_msgs;
242                         memcpy(&IMAP->msgids[i], &IMAP->msgids[i+1],
243                                 (sizeof(long)*(IMAP->num_msgs-i)) );
244                         memcpy(&IMAP->flags[i], &IMAP->flags[i+1],
245                                 (sizeof(long)*(IMAP->num_msgs-i)) );
246
247                         --i;
248                 }
249
250         }
251
252         /*
253          * Remember how many messages were here before we re-scanned.
254          */
255         original_num_msgs = IMAP->num_msgs;
256         if (IMAP->num_msgs > 0) {
257                 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
258         }
259         else {
260                 original_highest = 0L;
261         }
262
263         /*
264          * Now peruse the room for *new* messages only.
265          */
266         if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
267                 if (msglist[j] > original_highest) {
268                         imap_add_single_msgid(msglist[j], NULL);
269                 }
270         }
271         imap_set_seen_flags();
272
273         /*
274          * If new messages have arrived, tell the client about them.
275          */
276         if (IMAP->num_msgs > original_num_msgs) {
277                 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
278         }
279
280         if (num_msgs != 0) phree(msglist);
281 }
282
283
284
285
286
287
288
289 /*
290  * This cleanup function blows away the temporary memory and files used by
291  * the IMAP server.
292  */
293 void imap_cleanup_function(void) {
294
295         /* Don't do this stuff if this is not a IMAP session! */
296         if (CC->h_command_function != imap_command_loop) return;
297
298         lprintf(9, "Performing IMAP cleanup hook\n");
299         imap_free_msgids();
300         imap_free_transmitted_message();
301         lprintf(9, "Finished IMAP cleanup hook\n");
302 }
303
304
305
306 /*
307  * Here's where our IMAP session begins its happy day.
308  */
309 void imap_greeting(void) {
310
311         strcpy(CC->cs_clientname, "IMAP session");
312         CtdlAllocUserData(SYM_IMAP, sizeof(struct citimap));
313         IMAP->authstate = imap_as_normal;
314
315         cprintf("* OK %s Citadel/UX IMAP4rev1 server ready\r\n",
316                 config.c_fqdn);
317 }
318
319
320 /*
321  * implements the LOGIN command (ordinary username/password login)
322  */
323 void imap_login(int num_parms, char *parms[]) {
324         if (CtdlLoginExistingUser(parms[2]) == login_ok) {
325                 if (CtdlTryPassword(parms[3]) == pass_ok) {
326                         cprintf("%s OK login successful\r\n", parms[0]);
327                         return;
328                 }
329         }
330
331         cprintf("%s BAD Login incorrect\r\n", parms[0]);
332 }
333
334
335 /*
336  * Implements the AUTHENTICATE command
337  */
338 void imap_authenticate(int num_parms, char *parms[]) {
339         char buf[SIZ];
340
341         if (num_parms != 3) {
342                 cprintf("%s BAD incorrect number of parameters\r\n",
343                         parms[0]);
344                 return;
345         }
346
347         if (CC->logged_in) {
348                 cprintf("%s BAD Already logged in.\r\n", parms[0]);
349                 return;
350         }
351
352         if (!strcasecmp(parms[2], "LOGIN")) {
353                 CtdlEncodeBase64(buf, "Username:", 9);
354                 cprintf("+ %s\r\n", buf);
355                 IMAP->authstate = imap_as_expecting_username;
356                 strcpy(IMAP->authseq, parms[0]);
357                 return;
358         }
359
360         else {
361                 cprintf("%s NO AUTHENTICATE %s failed\r\n",
362                         parms[0], parms[1]);
363         }
364 }
365
366 void imap_auth_login_user(char *cmd) {
367         char buf[SIZ];
368
369         CtdlDecodeBase64(buf, cmd, SIZ);
370         CtdlLoginExistingUser(buf);
371         CtdlEncodeBase64(buf, "Password:", 9);
372         cprintf("+ %s\r\n", buf);
373         IMAP->authstate = imap_as_expecting_password;
374         return;
375 }
376
377 void imap_auth_login_pass(char *cmd) {
378         char buf[SIZ];
379
380         CtdlDecodeBase64(buf, cmd, SIZ);
381         if (CtdlTryPassword(buf) == pass_ok) {
382                 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
383         }
384         else {
385                 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
386         }
387         IMAP->authstate = imap_as_normal;
388         return;
389 }
390
391
392 /*
393  * implements the CAPABILITY command
394  */
395 void imap_capability(int num_parms, char *parms[]) {
396         cprintf("* CAPABILITY IMAP4 IMAP4REV1 AUTH=LOGIN");
397
398 #ifdef HAVE_OPENSSL_XXX /* temporarily disabled due to bugs */
399         cprintf(" STARTTLS");
400 #endif
401
402         cprintf("\r\n");
403         cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
404 }
405
406
407 /*
408  * implements the STARTTLS command
409  */
410 #ifdef HAVE_OPENSSL_XXX /* temporarily disabled due to bugs */
411 void imap_starttls(int num_parms, char *parms[]) {
412         int retval, bits, alg_bits;
413
414         if (!ssl_ctx) {
415                 cprintf("%s NO No SSL_CTX available\r\n", parms[0]);
416                 return;
417         }
418         if (!(CC->ssl = SSL_new(ssl_ctx))) {
419                 lprintf(2, "SSL_new failed: %s\n",
420                                 ERR_reason_error_string(ERR_peek_error()));
421                 cprintf("%s NO SSL_new: %s\r\n", parms[0],
422                                 ERR_reason_error_string(ERR_get_error()));
423                 return;
424         }
425         if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
426                 lprintf(2, "SSL_set_fd failed: %s\n",
427                                 ERR_reason_error_string(ERR_peek_error()));
428                 SSL_free(CC->ssl);
429                 CC->ssl = NULL;
430                 cprintf("%s NO SSL_set_fd: %s\r\n", parms[0],
431                                 ERR_reason_error_string(ERR_get_error()));
432                 return;
433         }
434         cprintf("%s OK begin TLS negotiation now\r\n", parms[0]);
435         retval = SSL_accept(CC->ssl);
436         if (retval < 1) {
437                 /*
438                  * Can't notify the client of an error here; they will
439                  * discover the problem at the SSL layer and should
440                  * revert to unencrypted communications.
441                  */
442                 long errval;
443
444                 errval = SSL_get_error(CC->ssl, retval);
445                 lprintf(2, "SSL_accept failed: %s\n",
446                                 ERR_reason_error_string(ERR_get_error()));
447                 SSL_free(CC->ssl);
448                 CC->ssl = NULL;
449                 return;
450         }
451         BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
452         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
453         lprintf(3, "SSL/TLS using %s on %s (%d of %d bits)\n",
454                         SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
455                         SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
456                         bits, alg_bits);
457         CC->redirect_ssl = 1;
458 }
459 #endif
460
461
462
463 /*
464  * implements the SELECT command
465  */
466 void imap_select(int num_parms, char *parms[]) {
467         char towhere[SIZ];
468         char augmented_roomname[ROOMNAMELEN];
469         int c = 0;
470         int ok = 0;
471         int ra = 0;
472         struct ctdlroom QRscratch;
473         int msgs, new;
474         int floornum;
475         int roomflags;
476         int i;
477
478         /* Convert the supplied folder name to a roomname */
479         i = imap_roomname(towhere, sizeof towhere, parms[2]);
480         if (i < 0) {
481                 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
482                 IMAP->selected = 0;
483                 return;
484         }
485         floornum = (i & 0x00ff);
486         roomflags = (i & 0xff00);
487
488         /* First try a regular match */
489         c = getroom(&QRscratch, towhere);
490
491         /* Then try a mailbox name match */
492         if (c != 0) {
493                 MailboxName(augmented_roomname, sizeof augmented_roomname,
494                             &CC->user, towhere);
495                 c = getroom(&QRscratch, augmented_roomname);
496                 if (c == 0)
497                         strcpy(towhere, augmented_roomname);
498         }
499
500         /* If the room exists, check security/access */
501         if (c == 0) {
502                 /* See if there is an existing user/room relationship */
503                 ra = CtdlRoomAccess(&QRscratch, &CC->user);
504
505                 /* normal clients have to pass through security */
506                 if (ra & UA_KNOWN) {
507                         ok = 1;
508                 }
509         }
510
511         /* Fail here if no such room */
512         if (!ok) {
513                 cprintf("%s NO ... no such room, or access denied\r\n",
514                         parms[0]);
515                 /* IMAP->selected = 0; */
516                 return;
517         }
518
519         /* If we already had some other folder selected, auto-expunge it */
520         imap_do_expunge();
521
522         /*
523          * usergoto() formally takes us to the desired room, happily returning
524          * the number of messages and number of new messages.
525          */
526         memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
527         usergoto(NULL, 0, 0, &msgs, &new);
528         IMAP->selected = 1;
529
530         if (!strcasecmp(parms[1], "EXAMINE")) {
531                 IMAP->readonly = 1;
532         }
533         else {
534                 IMAP->readonly = 0;
535         }
536
537         imap_load_msgids();
538
539         cprintf("* %d EXISTS\r\n", msgs);
540         cprintf("* %d RECENT\r\n", new);
541
542         /* Note that \Deleted is a valid flag, but not a permanent flag,
543          * because we don't maintain its state across sessions.  Citadel
544          * automatically expunges mailboxes when they are de-selected.
545          */
546         cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
547         cprintf("* OK [PERMANENTFLAGS (\\Seen \\Answered)] "
548                 "permanent flags\r\n");
549
550         cprintf("* OK [UIDVALIDITY 0] UIDs valid\r\n");
551         cprintf("%s OK [%s] %s completed\r\n",
552                 parms[0],
553                 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"),
554                 parms[1]);
555 }
556
557
558
559 /*
560  * does the real work for expunge
561  */
562 int imap_do_expunge(void) {
563         int i;
564         int num_expunged = 0;
565
566         lprintf(9, "imap_do_expunge() called\n");
567         if (IMAP->selected == 0) return(0);
568
569         if (IMAP->num_msgs > 0) for (i=0; i<IMAP->num_msgs; ++i) {
570                 if (IMAP->flags[i] & IMAP_DELETED) {
571                         CtdlDeleteMessages(CC->room.QRname,
572                                         IMAP->msgids[i], "");
573                         ++num_expunged;
574                         lprintf(9, "%ld ... deleted\n", IMAP->msgids[i]);
575                 }
576                 else {
577                         lprintf(9, "%ld ... not deleted\n", IMAP->msgids[i]);
578                 }
579         }
580
581         if (num_expunged > 0) {
582                 imap_rescan_msgids();
583         }
584
585         return(num_expunged);
586 }
587
588
589 /*
590  * implements the EXPUNGE command syntax
591  */
592 void imap_expunge(int num_parms, char *parms[]) {
593         int num_expunged = 0;
594
595         num_expunged = imap_do_expunge();
596         cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
597 }
598
599
600 /*
601  * implements the CLOSE command
602  */
603 void imap_close(int num_parms, char *parms[]) {
604
605         /* Yes, we always expunge on close. */
606         imap_do_expunge();
607
608         IMAP->selected = 0;
609         IMAP->readonly = 0;
610         imap_free_msgids();
611         cprintf("%s OK CLOSE completed\r\n", parms[0]);
612 }
613
614
615
616
617 /*
618  * Used by LIST and LSUB to show the floors in the listing
619  */
620 void imap_list_floors(char *cmd, char *pattern) {
621         int i;
622         struct floor *fl;
623
624         for (i=0; i<MAXFLOORS; ++i) {
625                 fl = cgetfloor(i);
626                 if (fl->f_flags & F_INUSE) {
627                         if (imap_mailbox_matches_pattern(pattern, fl->f_name)) {
628                                 cprintf("* %s (\\NoSelect) \"|\" ", cmd);
629                                 imap_strout(fl->f_name);
630                                 cprintf("\r\n");
631                         }
632                 }
633         }
634 }
635
636
637
638 /*
639  * Back end for imap_lsub()
640  *
641  * IMAP "subscribed folder" is equivocated to Citadel "known rooms."  This
642  * may or may not be the desired behavior in the future.
643  */
644 void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data) {
645         char buf[SIZ];
646         int ra;
647         char *pattern;
648
649         pattern = (char *)data;
650
651         /* Only list rooms to which the user has access!! */
652         ra = CtdlRoomAccess(qrbuf, &CC->user);
653         if (ra & UA_KNOWN) {
654                 imap_mailboxname(buf, sizeof buf, qrbuf);
655                 if (imap_mailbox_matches_pattern(pattern, buf)) {
656                         cprintf("* LSUB () \"|\" ");
657                         imap_strout(buf);
658                         cprintf("\r\n");
659                 }
660         }
661 }
662
663
664 /*
665  * Implements the LSUB command
666  */
667 void imap_lsub(int num_parms, char *parms[]) {
668         char pattern[SIZ];
669         if (num_parms < 4) {
670                 cprintf("%s BAD arguments invalid\r\n", parms[0]);
671                 return;
672         }
673         snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
674
675         if (strlen(parms[3])==0) {
676                 cprintf("* LIST (\\Noselect) \"|\" \"\"\r\n");
677         }
678
679         else {
680                 imap_list_floors("LSUB", pattern);
681                 ForEachRoom(imap_lsub_listroom, pattern);
682         }
683
684         cprintf("%s OK LSUB completed\r\n", parms[0]);
685 }
686
687
688
689 /*
690  * Back end for imap_list()
691  */
692 void imap_list_listroom(struct ctdlroom *qrbuf, void *data) {
693         char buf[SIZ];
694         int ra;
695         char *pattern;
696
697         pattern = (char *)data;
698
699         /* Only list rooms to which the user has access!! */
700         ra = CtdlRoomAccess(qrbuf, &CC->user);
701         if ( (ra & UA_KNOWN) 
702           || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
703                 imap_mailboxname(buf, sizeof buf, qrbuf);
704                 if (imap_mailbox_matches_pattern(pattern, buf)) {
705                         cprintf("* LIST () \"|\" ");
706                         imap_strout(buf);
707                         cprintf("\r\n");
708                 }
709         }
710 }
711
712
713 /*
714  * Implements the LIST command
715  */
716 void imap_list(int num_parms, char *parms[]) {
717         char pattern[SIZ];
718         if (num_parms < 4) {
719                 cprintf("%s BAD arguments invalid\r\n", parms[0]);
720                 return;
721         }
722         snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
723
724         if (strlen(parms[3])==0) {
725                 cprintf("* LIST (\\Noselect) \"|\" \"\"\r\n");
726         }
727
728         else {
729                 imap_list_floors("LIST", pattern);
730                 ForEachRoom(imap_list_listroom, pattern);
731         }
732
733         cprintf("%s OK LIST completed\r\n", parms[0]);
734 }
735
736
737
738 /*
739  * Implements the CREATE command
740  *
741  */
742 void imap_create(int num_parms, char *parms[]) {
743         int ret;
744         char roomname[ROOMNAMELEN];
745         int floornum;
746         int flags;
747         int newroomtype;
748
749         if (strchr(parms[2], '\\') != NULL) {
750                 cprintf("%s NO Invalid character in folder name\r\n", parms[0]);
751                 return;
752         }
753
754         ret = imap_roomname(roomname, sizeof roomname, parms[2]);
755         if (ret < 0) {
756                 cprintf("%s NO Invalid mailbox name or location\r\n",
757                         parms[0]);
758                 return;
759         }
760         floornum = ( ret & 0x00ff );    /* lower 8 bits = floor number */
761         flags =    ( ret & 0xff00 );    /* upper 8 bits = flags        */
762
763         if (flags & IR_MAILBOX) {
764                 newroomtype = 4;        /* private mailbox */
765         }
766         else {
767                 newroomtype = 0;        /* public folder */
768         }
769
770         lprintf(7, "Create new room <%s> on floor <%d> with type <%d>\n",
771                 roomname, floornum, newroomtype);
772
773         ret = create_room(roomname, newroomtype, "", floornum, 1, 0);
774         if (ret == 0) {
775                 cprintf("%s NO Mailbox already exists, or create failed\r\n",
776                         parms[0]);
777         }
778         else {
779                 cprintf("%s OK CREATE completed\r\n", parms[0]);
780         }
781 }
782
783
784 /*
785  * Locate a room by its IMAP folder name, and check access to it
786  */
787 int imap_grabroom(char *returned_roomname, char *foldername) {
788         int ret;
789         char augmented_roomname[ROOMNAMELEN];
790         char roomname[ROOMNAMELEN];
791         int c;
792         struct ctdlroom QRscratch;
793         int ra;
794         int ok = 0;
795
796         ret = imap_roomname(roomname, sizeof roomname, foldername);
797         if (ret < 0) {
798                 return(1);
799         }
800
801         /* First try a regular match */
802         c = getroom(&QRscratch, roomname);
803
804         /* Then try a mailbox name match */
805         if (c != 0) {
806                 MailboxName(augmented_roomname, sizeof augmented_roomname,
807                             &CC->user, roomname);
808                 c = getroom(&QRscratch, augmented_roomname);
809                 if (c == 0)
810                         strcpy(roomname, augmented_roomname);
811         }
812
813         /* If the room exists, check security/access */
814         if (c == 0) {
815                 /* See if there is an existing user/room relationship */
816                 ra = CtdlRoomAccess(&QRscratch, &CC->user);
817
818                 /* normal clients have to pass through security */
819                 if (ra & UA_KNOWN) {
820                         ok = 1;
821                 }
822         }
823
824         /* Fail here if no such room */
825         if (!ok) {
826                 strcpy(returned_roomname, "");
827                 return(2);
828         }
829         else {
830                 strcpy(returned_roomname, QRscratch.QRname);
831                 return(0);
832         }
833 }
834
835
836 /*
837  * Implements the STATUS command (sort of)
838  *
839  */
840 void imap_status(int num_parms, char *parms[]) {
841         int ret;
842         char roomname[ROOMNAMELEN];
843         char buf[SIZ];
844         char savedroom[ROOMNAMELEN];
845         int msgs, new;
846
847         ret = imap_grabroom(roomname, parms[2]);
848         if (ret != 0) {
849                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
850                         parms[0]);
851                 return;
852         }
853
854         /*
855          * usergoto() formally takes us to the desired room, happily returning
856          * the number of messages and number of new messages.  (If another
857          * folder is selected, save its name so we can return there!!!!!)
858          */
859         if (IMAP->selected) {
860                 strcpy(savedroom, CC->room.QRname);
861         }
862         usergoto(roomname, 0, 0, &msgs, &new);
863
864         /*
865          * Tell the client what it wants to know.  In fact, tell it *more* than
866          * it wants to know.  We happily IGnore the supplied status data item
867          * names and simply spew all possible data items.  It's far easier to
868          * code and probably saves us some processing time too.
869          */
870         imap_mailboxname(buf, sizeof buf, &CC->room);
871         cprintf("* STATUS ");
872         imap_strout(buf);
873         cprintf(" (MESSAGES %d ", msgs);
874         cprintf("RECENT 0 ");   /* FIXME we need to implement this */
875         cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
876         cprintf("UNSEEN %d)\r\n", new);
877
878         /*
879          * If another folder is selected, go back to that room so we can resume
880          * our happy day without violent explosions.
881          */
882         if (IMAP->selected) {
883                 usergoto(savedroom, 0, 0, &msgs, &new);
884         }
885
886         /*
887          * Oooh, look, we're done!
888          */
889         cprintf("%s OK STATUS completed\r\n", parms[0]);
890 }
891
892
893
894 /*
895  * Implements the SUBSCRIBE command
896  *
897  */
898 void imap_subscribe(int num_parms, char *parms[]) {
899         int ret;
900         char roomname[ROOMNAMELEN];
901         char savedroom[ROOMNAMELEN];
902         int msgs, new;
903
904         ret = imap_grabroom(roomname, parms[2]);
905         if (ret != 0) {
906                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
907                         parms[0]);
908                 return;
909         }
910
911         /*
912          * usergoto() formally takes us to the desired room, which has the side
913          * effect of marking the room as not-zapped ... exactly the effect
914          * we're looking for.
915          */
916         if (IMAP->selected) {
917                 strcpy(savedroom, CC->room.QRname);
918         }
919         usergoto(roomname, 0, 0, &msgs, &new);
920
921         /*
922          * If another folder is selected, go back to that room so we can resume
923          * our happy day without violent explosions.
924          */
925         if (IMAP->selected) {
926                 usergoto(savedroom, 0, 0, &msgs, &new);
927         }
928
929         cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
930 }
931
932
933 /*
934  * Implements the UNSUBSCRIBE command
935  *
936  */
937 void imap_unsubscribe(int num_parms, char *parms[]) {
938         int ret;
939         char roomname[ROOMNAMELEN];
940         char savedroom[ROOMNAMELEN];
941         int msgs, new;
942
943         ret = imap_grabroom(roomname, parms[2]);
944         if (ret != 0) {
945                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
946                         parms[0]);
947                 return;
948         }
949
950         /*
951          * usergoto() formally takes us to the desired room.
952          */
953         if (IMAP->selected) {
954                 strcpy(savedroom, CC->room.QRname);
955         }
956         usergoto(roomname, 0, 0, &msgs, &new);
957
958         /* 
959          * Now make the API call to zap the room
960          */
961         if (CtdlForgetThisRoom() == 0) {
962                 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
963         }
964         else {
965                 cprintf("%s NO You may not unsubscribe from this folder.\r\n",
966                         parms[0]);
967         }
968
969         /*
970          * If another folder is selected, go back to that room so we can resume
971          * our happy day without violent explosions.
972          */
973         if (IMAP->selected) {
974                 usergoto(savedroom, 0, 0, &msgs, &new);
975         }
976 }
977
978
979
980 /*
981  * Implements the DELETE command
982  *
983  */
984 void imap_delete(int num_parms, char *parms[]) {
985         int ret;
986         char roomname[ROOMNAMELEN];
987         char savedroom[ROOMNAMELEN];
988         int msgs, new;
989
990         ret = imap_grabroom(roomname, parms[2]);
991         if (ret != 0) {
992                 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
993                         parms[0]);
994                 return;
995         }
996
997         /*
998          * usergoto() formally takes us to the desired room, happily returning
999          * the number of messages and number of new messages.  (If another
1000          * folder is selected, save its name so we can return there!!!!!)
1001          */
1002         if (IMAP->selected) {
1003                 strcpy(savedroom, CC->room.QRname);
1004         }
1005         usergoto(roomname, 0, 0, &msgs, &new);
1006
1007         /*
1008          * Now delete the room.
1009          */
1010         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1011                 cprintf("%s OK DELETE completed\r\n", parms[0]);
1012                 delete_room(&CC->room);
1013         }
1014         else {
1015                 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1016         }
1017
1018         /*
1019          * If another folder is selected, go back to that room so we can resume
1020          * our happy day without violent explosions.
1021          */
1022         if (IMAP->selected) {
1023                 usergoto(savedroom, 0, 0, &msgs, &new);
1024         }
1025 }
1026
1027
1028 /*
1029  * Back end function for imap_rename()
1030  */
1031 void imap_rename_backend(struct ctdlroom *qrbuf, void *data) {
1032         char foldername[SIZ];
1033         char newfoldername[SIZ];
1034         char newroomname[ROOMNAMELEN];
1035         int newfloor = 0;
1036         struct irl *irlp = NULL;        /* scratch pointer */
1037         struct irlparms *irlparms;
1038
1039         irlparms = (struct irlparms *)data;
1040         imap_mailboxname(foldername, sizeof foldername, qrbuf);
1041
1042         /* Rename subfolders */
1043         if ( (!strncasecmp(foldername, irlparms->oldname,
1044            strlen(irlparms->oldname))
1045            && (foldername[strlen(irlparms->oldname)] == '|')) ) {
1046
1047                 sprintf(newfoldername, "%s|%s",
1048                         irlparms->newname,
1049                         &foldername[strlen(irlparms->oldname)+1]
1050                 );
1051
1052                 newfloor = imap_roomname(newroomname,
1053                         sizeof newroomname, newfoldername) & 0xFF;
1054
1055                 irlp = (struct irl *) mallok(sizeof(struct irl));
1056                 strcpy(irlp->irl_newroom, newroomname);
1057                 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1058                 irlp->irl_newfloor = newfloor;
1059                 irlp->next = *(irlparms->irl);
1060                 *(irlparms->irl) = irlp;
1061         }
1062 }
1063         
1064
1065 /*
1066  * Implements the RENAME command
1067  *
1068  */
1069 void imap_rename(int num_parms, char *parms[]) {
1070         char old_room[ROOMNAMELEN];
1071         char new_room[ROOMNAMELEN];
1072         int oldr, newr;
1073         int new_floor;
1074         int r;
1075         struct irl *irl = NULL;         /* the list */
1076         struct irl *irlp = NULL;        /* scratch pointer */
1077         struct irlparms irlparms;
1078
1079         if (strchr(parms[3], '\\') != NULL) {
1080                 cprintf("%s NO Invalid character in folder name\r\n", parms[0]);
1081                 return;
1082         }
1083
1084         oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1085         newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1086         new_floor = (newr & 0xFF);
1087
1088         r = CtdlRenameRoom(old_room, new_room, new_floor);
1089
1090         if (r == crr_room_not_found) {
1091                 cprintf("%s NO Could not locate this folder\r\n", parms[0]);
1092                 return;
1093         }
1094         if (r == crr_already_exists) {
1095                 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1096                 return;
1097         }
1098         if (r == crr_noneditable) {
1099                 cprintf("%s This folder is not editable.\r\n", parms[0]);
1100                 return;
1101         }
1102         if (r == crr_invalid_floor) {
1103                 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1104                 return;
1105         }
1106         if (r == crr_access_denied) {
1107                 cprintf("%s You do not have permission to edit "
1108                         "this folder.\r\n", parms[0]);
1109                 return;
1110         }
1111         if (r != crr_ok) {
1112                 cprintf("%s NO Rename failed - undefined error %d\r\n",
1113                         parms[0], r);
1114                 return;
1115         }
1116
1117
1118         /* If this is the INBOX, then RFC2060 says we have to just move the
1119          * contents.  In a Citadel environment it's easier to rename the room
1120          * (already did that) and create a new inbox.
1121          */
1122         if (!strcasecmp(parms[2], "INBOX")) {
1123                 create_room(MAILROOM, 4, "", 0, 1, 0);
1124         }
1125
1126         /* Otherwise, do the subfolders.  Build a list of rooms to rename... */
1127         else {
1128                 irlparms.oldname = parms[2];
1129                 irlparms.newname = parms[3];
1130                 irlparms.irl = &irl;
1131                 ForEachRoom(imap_rename_backend, (void *)&irlparms);
1132
1133                 /* ... and now rename them. */
1134                 while (irl != NULL) {
1135                         r = CtdlRenameRoom(irl->irl_oldroom,
1136                                 irl->irl_newroom, irl->irl_newfloor);
1137                         if (r != crr_ok) {
1138                                 /* FIXME handle error returns better */
1139                                 lprintf(5, "CtdlRenameRoom() error %d\n", r);
1140                         }
1141                         irlp = irl;
1142                         irl = irl->next;
1143                         phree(irlp);
1144                 }
1145         }
1146
1147         cprintf("%s OK RENAME completed\r\n", parms[0]);
1148 }
1149
1150
1151
1152
1153 /* 
1154  * Main command loop for IMAP sessions.
1155  */
1156 void imap_command_loop(void) {
1157         char cmdbuf[SIZ];
1158         char *parms[SIZ];
1159         int num_parms;
1160
1161         time(&CC->lastcmd);
1162         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1163         if (client_gets(cmdbuf) < 1) {
1164                 lprintf(3, "IMAP socket is broken.  Ending session.\r\n");
1165                 CC->kill_me = 1;
1166                 return;
1167         }
1168
1169         lprintf(5, "IMAP: %s\r\n", cmdbuf);
1170         while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
1171
1172
1173         /* strip off l/t whitespace and CRLF */
1174         if (cmdbuf[strlen(cmdbuf)-1]=='\n') cmdbuf[strlen(cmdbuf)-1]=0;
1175         if (cmdbuf[strlen(cmdbuf)-1]=='\r') cmdbuf[strlen(cmdbuf)-1]=0;
1176         striplt(cmdbuf);
1177
1178         /* If we're in the middle of a multi-line command, handle that */
1179         if (IMAP->authstate == imap_as_expecting_username) {
1180                 imap_auth_login_user(cmdbuf);
1181                 return;
1182         }
1183         if (IMAP->authstate == imap_as_expecting_password) {
1184                 imap_auth_login_pass(cmdbuf);
1185                 return;
1186         }
1187
1188
1189         /* Ok, at this point we're in normal command mode.  The first thing
1190          * we do is print any incoming pages (yeah! we really do!)
1191          */
1192         imap_print_express_messages();
1193
1194         /*
1195          * Before processing the command that was just entered... if we happen
1196          * to have a folder selected, we'd like to rescan that folder for new
1197          * messages, and for deletions/changes of existing messages.  This
1198          * could probably be optimized somehow, but IMAP sucks...
1199          */
1200         if (IMAP->selected) {
1201                 imap_rescan_msgids();
1202         }
1203
1204         /* Now for the command set. */
1205
1206         /* Grab the tag, command, and parameters.  Check syntax. */
1207         num_parms = imap_parameterize(parms, cmdbuf);
1208         if (num_parms < 2) {
1209                 cprintf("BAD syntax error\r\n");
1210         }
1211
1212         /* The commands below may be executed in any state */
1213
1214         else if ( (!strcasecmp(parms[1], "NOOP"))
1215            || (!strcasecmp(parms[1], "CHECK")) ) {
1216                 cprintf("%s OK This command successfully did nothing.\r\n",
1217                         parms[0]);
1218         }
1219
1220         else if (!strcasecmp(parms[1], "LOGOUT")) {
1221                 imap_do_expunge();      /* yes, we auto-expunge */
1222                 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1223                 cprintf("%s OK thank you for using Citadel IMAP\r\n", parms[0]);
1224                 CC->kill_me = 1;
1225                 return;
1226         }
1227
1228         else if (!strcasecmp(parms[1], "LOGIN")) {
1229                 imap_login(num_parms, parms);
1230         }
1231
1232         else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1233                 imap_authenticate(num_parms, parms);
1234         }
1235
1236         else if (!strcasecmp(parms[1], "CAPABILITY")) {
1237                 imap_capability(num_parms, parms);
1238         }
1239
1240 #ifdef HAVE_OPENSSL_XXX /* temporarily disabled due to bugs */
1241         else if (!strcasecmp(parms[1], "STARTTLS")) {
1242                 imap_starttls(num_parms, parms);
1243         }
1244 #endif
1245
1246         else if (!CC->logged_in) {
1247                 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1248         }
1249
1250         /* The commans below require a logged-in state */
1251
1252         else if (!strcasecmp(parms[1], "SELECT")) {
1253                 imap_select(num_parms, parms);
1254         }
1255
1256         else if (!strcasecmp(parms[1], "EXAMINE")) {
1257                 imap_select(num_parms, parms);
1258         }
1259
1260         else if (!strcasecmp(parms[1], "LSUB")) {
1261                 imap_lsub(num_parms, parms);
1262         }
1263
1264         else if (!strcasecmp(parms[1], "LIST")) {
1265                 imap_list(num_parms, parms);
1266         }
1267
1268         else if (!strcasecmp(parms[1], "CREATE")) {
1269                 imap_create(num_parms, parms);
1270         }
1271
1272         else if (!strcasecmp(parms[1], "DELETE")) {
1273                 imap_delete(num_parms, parms);
1274         }
1275
1276         else if (!strcasecmp(parms[1], "RENAME")) {
1277                 imap_rename(num_parms, parms);
1278         }
1279
1280         else if (!strcasecmp(parms[1], "STATUS")) {
1281                 imap_status(num_parms, parms);
1282         }
1283
1284         else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1285                 imap_subscribe(num_parms, parms);
1286         }
1287
1288         else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1289                 imap_unsubscribe(num_parms, parms);
1290         }
1291
1292         else if (!strcasecmp(parms[1], "APPEND")) {
1293                 imap_append(num_parms, parms);
1294         }
1295
1296         else if (IMAP->selected == 0) {
1297                 cprintf("%s BAD no folder selected\r\n", parms[0]);
1298         }
1299
1300         /* The commands below require the SELECT state on a mailbox */
1301
1302         else if (!strcasecmp(parms[1], "FETCH")) {
1303                 imap_fetch(num_parms, parms);
1304         }
1305
1306         else if ( (!strcasecmp(parms[1], "UID"))
1307                 && (!strcasecmp(parms[2], "FETCH")) ) {
1308                 imap_uidfetch(num_parms, parms);
1309         }
1310
1311         else if (!strcasecmp(parms[1], "SEARCH")) {
1312                 imap_search(num_parms, parms);
1313         }
1314
1315         else if ( (!strcasecmp(parms[1], "UID"))
1316                 && (!strcasecmp(parms[2], "SEARCH")) ) {
1317                 imap_uidsearch(num_parms, parms);
1318         }
1319
1320         else if (!strcasecmp(parms[1], "STORE")) {
1321                 imap_store(num_parms, parms);
1322         }
1323
1324         else if ( (!strcasecmp(parms[1], "UID"))
1325                 && (!strcasecmp(parms[2], "STORE")) ) {
1326                 imap_uidstore(num_parms, parms);
1327         }
1328
1329         else if (!strcasecmp(parms[1], "COPY")) {
1330                 imap_copy(num_parms, parms);
1331         }
1332
1333         else if ( (!strcasecmp(parms[1], "UID"))
1334                 && (!strcasecmp(parms[2], "COPY")) ) {
1335                 imap_uidcopy(num_parms, parms);
1336         }
1337
1338         else if (!strcasecmp(parms[1], "EXPUNGE")) {
1339                 imap_expunge(num_parms, parms);
1340         }
1341
1342         else if (!strcasecmp(parms[1], "CLOSE")) {
1343                 imap_close(num_parms, parms);
1344         }
1345
1346         /* End of commands.  If we get here, the command is either invalid
1347          * or unimplemented.
1348          */
1349
1350         else {
1351                 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1352         }
1353
1354         /* If the client transmitted a message we can free it now */
1355         imap_free_transmitted_message();
1356 }
1357
1358
1359
1360 /*
1361  * This function is called to register the IMAP extension with Citadel.
1362  */
1363 char *serv_imap_init(void)
1364 {
1365         CtdlRegisterServiceHook(config.c_imap_port,
1366                                 NULL,
1367                                 imap_greeting,
1368                                 imap_command_loop);
1369         CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1370         return "$Id$";
1371 }