]> code.citadel.org Git - citadel.git/blob - citadel/serv_imap.c
* Changes to auto-expunge algorithm to support correct behavior in
[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", parms[0]);
343                 return;
344         }
345
346         if (!strcasecmp(parms[2], "LOGIN")) {
347                 CtdlEncodeBase64(buf, "Username:", 9);
348                 cprintf("+ %s\r\n", buf);
349                 IMAP->authstate = imap_as_expecting_username;
350                 strcpy(IMAP->authseq, parms[0]);
351                 return;
352         }
353
354         else {
355                 cprintf("%s NO AUTHENTICATE %s failed\r\n",
356                         parms[0], parms[1]);
357         }
358 }
359
360 void imap_auth_login_user(char *cmd) {
361         char buf[SIZ];
362
363         CtdlDecodeBase64(buf, cmd, SIZ);
364         CtdlLoginExistingUser(buf);
365         CtdlEncodeBase64(buf, "Password:", 9);
366         cprintf("+ %s\r\n", buf);
367         IMAP->authstate = imap_as_expecting_password;
368         return;
369 }
370
371 void imap_auth_login_pass(char *cmd) {
372         char buf[SIZ];
373
374         CtdlDecodeBase64(buf, cmd, SIZ);
375         if (CtdlTryPassword(buf) == pass_ok) {
376                 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
377         }
378         else {
379                 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
380         }
381         IMAP->authstate = imap_as_normal;
382         return;
383 }
384
385
386
387 /*
388  * implements the CAPABILITY command
389  */
390 void imap_capability(int num_parms, char *parms[]) {
391         cprintf("* CAPABILITY IMAP4 IMAP4REV1 AUTH=LOGIN");
392
393 #ifdef HAVE_OPENSSL_XXX /* temporarily disabled due to bugs */
394         cprintf(" STARTTLS");
395 #endif
396
397         cprintf("\r\n");
398         cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
399 }
400
401
402 /*
403  * implements the STARTTLS command
404  */
405 #ifdef HAVE_OPENSSL_XXX /* temporarily disabled due to bugs */
406 void imap_starttls(int num_parms, char *parms[]) {
407         int retval, bits, alg_bits;
408
409         if (!ssl_ctx) {
410                 cprintf("%s NO No SSL_CTX available\r\n", parms[0]);
411                 return;
412         }
413         if (!(CC->ssl = SSL_new(ssl_ctx))) {
414                 lprintf(2, "SSL_new failed: %s\n",
415                                 ERR_reason_error_string(ERR_peek_error()));
416                 cprintf("%s NO SSL_new: %s\r\n", parms[0],
417                                 ERR_reason_error_string(ERR_get_error()));
418                 return;
419         }
420         if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
421                 lprintf(2, "SSL_set_fd failed: %s\n",
422                                 ERR_reason_error_string(ERR_peek_error()));
423                 SSL_free(CC->ssl);
424                 CC->ssl = NULL;
425                 cprintf("%s NO SSL_set_fd: %s\r\n", parms[0],
426                                 ERR_reason_error_string(ERR_get_error()));
427                 return;
428         }
429         cprintf("%s OK begin TLS negotiation now\r\n", parms[0]);
430         retval = SSL_accept(CC->ssl);
431         if (retval < 1) {
432                 /*
433                  * Can't notify the client of an error here; they will
434                  * discover the problem at the SSL layer and should
435                  * revert to unencrypted communications.
436                  */
437                 long errval;
438
439                 errval = SSL_get_error(CC->ssl, retval);
440                 lprintf(2, "SSL_accept failed: %s\n",
441                                 ERR_reason_error_string(ERR_get_error()));
442                 SSL_free(CC->ssl);
443                 CC->ssl = NULL;
444                 return;
445         }
446         BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
447         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
448         lprintf(3, "SSL/TLS using %s on %s (%d of %d bits)\n",
449                         SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
450                         SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
451                         bits, alg_bits);
452         CC->redirect_ssl = 1;
453 }
454 #endif
455
456
457
458 /*
459  * implements the SELECT command
460  */
461 void imap_select(int num_parms, char *parms[]) {
462         char towhere[SIZ];
463         char augmented_roomname[ROOMNAMELEN];
464         int c = 0;
465         int ok = 0;
466         int ra = 0;
467         struct ctdlroom QRscratch;
468         int msgs, new;
469         int floornum;
470         int roomflags;
471         int i;
472
473         /* Convert the supplied folder name to a roomname */
474         i = imap_roomname(towhere, sizeof towhere, parms[2]);
475         if (i < 0) {
476                 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
477                 IMAP->selected = 0;
478                 return;
479         }
480         floornum = (i & 0x00ff);
481         roomflags = (i & 0xff00);
482
483         /* First try a regular match */
484         c = getroom(&QRscratch, towhere);
485
486         /* Then try a mailbox name match */
487         if (c != 0) {
488                 MailboxName(augmented_roomname, sizeof augmented_roomname,
489                             &CC->user, towhere);
490                 c = getroom(&QRscratch, augmented_roomname);
491                 if (c == 0)
492                         strcpy(towhere, augmented_roomname);
493         }
494
495         /* If the room exists, check security/access */
496         if (c == 0) {
497                 /* See if there is an existing user/room relationship */
498                 ra = CtdlRoomAccess(&QRscratch, &CC->user);
499
500                 /* normal clients have to pass through security */
501                 if (ra & UA_KNOWN) {
502                         ok = 1;
503                 }
504         }
505
506         /* Fail here if no such room */
507         if (!ok) {
508                 cprintf("%s NO ... no such room, or access denied\r\n",
509                         parms[0]);
510                 /* IMAP->selected = 0; */
511                 return;
512         }
513
514         /* If we already had some other folder selected, auto-expunge it */
515         imap_do_expunge();
516
517         /*
518          * usergoto() formally takes us to the desired room, happily returning
519          * the number of messages and number of new messages.
520          */
521         memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
522         usergoto(NULL, 0, 0, &msgs, &new);
523         IMAP->selected = 1;
524
525         if (!strcasecmp(parms[1], "EXAMINE")) {
526                 IMAP->readonly = 1;
527         }
528         else {
529                 IMAP->readonly = 0;
530         }
531
532         imap_load_msgids();
533
534         cprintf("* %d EXISTS\r\n", msgs);
535         cprintf("* %d RECENT\r\n", new);
536
537         /* Note that \Deleted is a valid flag, but not a permanent flag,
538          * because we don't maintain its state across sessions.  Citadel
539          * automatically expunges mailboxes when they are de-selected.
540          */
541         cprintf("* FLAGS (\\Deleted \\Seen \\Answered)\r\n");
542         cprintf("* OK [PERMANENTFLAGS (\\Seen \\Answered)] "
543                 "permanent flags\r\n");
544
545         cprintf("* OK [UIDVALIDITY 0] UIDs valid\r\n");
546         cprintf("%s OK [%s] %s completed\r\n",
547                 parms[0],
548                 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"),
549                 parms[1]);
550 }
551
552
553
554 /*
555  * does the real work for expunge
556  */
557 int imap_do_expunge(void) {
558         int i;
559         int num_expunged = 0;
560
561         lprintf(9, "imap_do_expunge() called\n");
562         if (IMAP->selected == 0) return(0);
563
564         if (IMAP->num_msgs > 0) for (i=0; i<IMAP->num_msgs; ++i) {
565                 if (IMAP->flags[i] & IMAP_DELETED) {
566                         CtdlDeleteMessages(CC->room.QRname,
567                                         IMAP->msgids[i], "");
568                         ++num_expunged;
569                         lprintf(9, "%ld ... deleted\n", IMAP->msgids[i]);
570                 }
571                 else {
572                         lprintf(9, "%ld ... not deleted\n", IMAP->msgids[i]);
573                 }
574         }
575
576         if (num_expunged > 0) {
577                 imap_rescan_msgids();
578         }
579
580         return(num_expunged);
581 }
582
583
584 /*
585  * implements the EXPUNGE command syntax
586  */
587 void imap_expunge(int num_parms, char *parms[]) {
588         int num_expunged = 0;
589
590         num_expunged = imap_do_expunge();
591         cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
592 }
593
594
595 /*
596  * implements the CLOSE command
597  */
598 void imap_close(int num_parms, char *parms[]) {
599
600         /* Yes, we always expunge on close. */
601         imap_do_expunge();
602
603         IMAP->selected = 0;
604         IMAP->readonly = 0;
605         imap_free_msgids();
606         cprintf("%s OK CLOSE completed\r\n", parms[0]);
607 }
608
609
610
611
612 /*
613  * Used by LIST and LSUB to show the floors in the listing
614  */
615 void imap_list_floors(char *cmd, char *pattern) {
616         int i;
617         struct floor *fl;
618
619         for (i=0; i<MAXFLOORS; ++i) {
620                 fl = cgetfloor(i);
621                 if (fl->f_flags & F_INUSE) {
622                         if (imap_mailbox_matches_pattern(pattern, fl->f_name)) {
623                                 cprintf("* %s (\\NoSelect) \"|\" ", cmd);
624                                 imap_strout(fl->f_name);
625                                 cprintf("\r\n");
626                         }
627                 }
628         }
629 }
630
631
632
633 /*
634  * Back end for imap_lsub()
635  *
636  * IMAP "subscribed folder" is equivocated to Citadel "known rooms."  This
637  * may or may not be the desired behavior in the future.
638  */
639 void imap_lsub_listroom(struct ctdlroom *qrbuf, void *data) {
640         char buf[SIZ];
641         int ra;
642         char *pattern;
643
644         pattern = (char *)data;
645
646         /* Only list rooms to which the user has access!! */
647         ra = CtdlRoomAccess(qrbuf, &CC->user);
648         if (ra & UA_KNOWN) {
649                 imap_mailboxname(buf, sizeof buf, qrbuf);
650                 if (imap_mailbox_matches_pattern(pattern, buf)) {
651                         cprintf("* LSUB () \"|\" ");
652                         imap_strout(buf);
653                         cprintf("\r\n");
654                 }
655         }
656 }
657
658
659 /*
660  * Implements the LSUB command
661  */
662 void imap_lsub(int num_parms, char *parms[]) {
663         char pattern[SIZ];
664         if (num_parms < 4) {
665                 cprintf("%s BAD arguments invalid\r\n", parms[0]);
666                 return;
667         }
668         snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
669
670         if (strlen(parms[3])==0) {
671                 cprintf("* LIST (\\Noselect) \"|\" \"\"\r\n");
672         }
673
674         else {
675                 imap_list_floors("LSUB", pattern);
676                 ForEachRoom(imap_lsub_listroom, pattern);
677         }
678
679         cprintf("%s OK LSUB completed\r\n", parms[0]);
680 }
681
682
683
684 /*
685  * Back end for imap_list()
686  */
687 void imap_list_listroom(struct ctdlroom *qrbuf, void *data) {
688         char buf[SIZ];
689         int ra;
690         char *pattern;
691
692         pattern = (char *)data;
693
694         /* Only list rooms to which the user has access!! */
695         ra = CtdlRoomAccess(qrbuf, &CC->user);
696         if ( (ra & UA_KNOWN) 
697           || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
698                 imap_mailboxname(buf, sizeof buf, qrbuf);
699                 if (imap_mailbox_matches_pattern(pattern, buf)) {
700                         cprintf("* LIST () \"|\" ");
701                         imap_strout(buf);
702                         cprintf("\r\n");
703                 }
704         }
705 }
706
707
708 /*
709  * Implements the LIST command
710  */
711 void imap_list(int num_parms, char *parms[]) {
712         char pattern[SIZ];
713         if (num_parms < 4) {
714                 cprintf("%s BAD arguments invalid\r\n", parms[0]);
715                 return;
716         }
717         snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
718
719         if (strlen(parms[3])==0) {
720                 cprintf("* LIST (\\Noselect) \"|\" \"\"\r\n");
721         }
722
723         else {
724                 imap_list_floors("LIST", pattern);
725                 ForEachRoom(imap_list_listroom, pattern);
726         }
727
728         cprintf("%s OK LIST completed\r\n", parms[0]);
729 }
730
731
732
733 /*
734  * Implements the CREATE command
735  *
736  */
737 void imap_create(int num_parms, char *parms[]) {
738         int ret;
739         char roomname[ROOMNAMELEN];
740         int floornum;
741         int flags;
742         int newroomtype;
743
744         if (strchr(parms[2], '\\') != NULL) {
745                 cprintf("%s NO Invalid character in folder name\r\n", parms[0]);
746                 return;
747         }
748
749         ret = imap_roomname(roomname, sizeof roomname, parms[2]);
750         if (ret < 0) {
751                 cprintf("%s NO Invalid mailbox name or location\r\n",
752                         parms[0]);
753                 return;
754         }
755         floornum = ( ret & 0x00ff );    /* lower 8 bits = floor number */
756         flags =    ( ret & 0xff00 );    /* upper 8 bits = flags        */
757
758         if (flags & IR_MAILBOX) {
759                 newroomtype = 4;        /* private mailbox */
760         }
761         else {
762                 newroomtype = 0;        /* public folder */
763         }
764
765         lprintf(7, "Create new room <%s> on floor <%d> with type <%d>\n",
766                 roomname, floornum, newroomtype);
767
768         ret = create_room(roomname, newroomtype, "", floornum, 1, 0);
769         if (ret == 0) {
770                 cprintf("%s NO Mailbox already exists, or create failed\r\n",
771                         parms[0]);
772         }
773         else {
774                 cprintf("%s OK CREATE completed\r\n", parms[0]);
775         }
776 }
777
778
779 /*
780  * Locate a room by its IMAP folder name, and check access to it
781  */
782 int imap_grabroom(char *returned_roomname, char *foldername) {
783         int ret;
784         char augmented_roomname[ROOMNAMELEN];
785         char roomname[ROOMNAMELEN];
786         int c;
787         struct ctdlroom QRscratch;
788         int ra;
789         int ok = 0;
790
791         ret = imap_roomname(roomname, sizeof roomname, foldername);
792         if (ret < 0) {
793                 return(1);
794         }
795
796         /* First try a regular match */
797         c = getroom(&QRscratch, roomname);
798
799         /* Then try a mailbox name match */
800         if (c != 0) {
801                 MailboxName(augmented_roomname, sizeof augmented_roomname,
802                             &CC->user, roomname);
803                 c = getroom(&QRscratch, augmented_roomname);
804                 if (c == 0)
805                         strcpy(roomname, augmented_roomname);
806         }
807
808         /* If the room exists, check security/access */
809         if (c == 0) {
810                 /* See if there is an existing user/room relationship */
811                 ra = CtdlRoomAccess(&QRscratch, &CC->user);
812
813                 /* normal clients have to pass through security */
814                 if (ra & UA_KNOWN) {
815                         ok = 1;
816                 }
817         }
818
819         /* Fail here if no such room */
820         if (!ok) {
821                 strcpy(returned_roomname, "");
822                 return(2);
823         }
824         else {
825                 strcpy(returned_roomname, QRscratch.QRname);
826                 return(0);
827         }
828 }
829
830
831 /*
832  * Implements the STATUS command (sort of)
833  *
834  */
835 void imap_status(int num_parms, char *parms[]) {
836         int ret;
837         char roomname[ROOMNAMELEN];
838         char buf[SIZ];
839         char savedroom[ROOMNAMELEN];
840         int msgs, new;
841
842         ret = imap_grabroom(roomname, parms[2]);
843         if (ret != 0) {
844                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
845                         parms[0]);
846                 return;
847         }
848
849         /*
850          * usergoto() formally takes us to the desired room, happily returning
851          * the number of messages and number of new messages.  (If another
852          * folder is selected, save its name so we can return there!!!!!)
853          */
854         if (IMAP->selected) {
855                 strcpy(savedroom, CC->room.QRname);
856         }
857         usergoto(roomname, 0, 0, &msgs, &new);
858
859         /*
860          * Tell the client what it wants to know.  In fact, tell it *more* than
861          * it wants to know.  We happily IGnore the supplied status data item
862          * names and simply spew all possible data items.  It's far easier to
863          * code and probably saves us some processing time too.
864          */
865         imap_mailboxname(buf, sizeof buf, &CC->room);
866         cprintf("* STATUS ");
867         imap_strout(buf);
868         cprintf(" (MESSAGES %d ", msgs);
869         cprintf("RECENT 0 ");   /* FIXME we need to implement this */
870         cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
871         cprintf("UNSEEN %d)\r\n", new);
872
873         /*
874          * If another folder is selected, go back to that room so we can resume
875          * our happy day without violent explosions.
876          */
877         if (IMAP->selected) {
878                 usergoto(savedroom, 0, 0, &msgs, &new);
879         }
880
881         /*
882          * Oooh, look, we're done!
883          */
884         cprintf("%s OK STATUS completed\r\n", parms[0]);
885 }
886
887
888
889 /*
890  * Implements the SUBSCRIBE command
891  *
892  */
893 void imap_subscribe(int num_parms, char *parms[]) {
894         int ret;
895         char roomname[ROOMNAMELEN];
896         char savedroom[ROOMNAMELEN];
897         int msgs, new;
898
899         ret = imap_grabroom(roomname, parms[2]);
900         if (ret != 0) {
901                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
902                         parms[0]);
903                 return;
904         }
905
906         /*
907          * usergoto() formally takes us to the desired room, which has the side
908          * effect of marking the room as not-zapped ... exactly the effect
909          * we're looking for.
910          */
911         if (IMAP->selected) {
912                 strcpy(savedroom, CC->room.QRname);
913         }
914         usergoto(roomname, 0, 0, &msgs, &new);
915
916         /*
917          * If another folder is selected, go back to that room so we can resume
918          * our happy day without violent explosions.
919          */
920         if (IMAP->selected) {
921                 usergoto(savedroom, 0, 0, &msgs, &new);
922         }
923
924         cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
925 }
926
927
928 /*
929  * Implements the UNSUBSCRIBE command
930  *
931  */
932 void imap_unsubscribe(int num_parms, char *parms[]) {
933         int ret;
934         char roomname[ROOMNAMELEN];
935         char savedroom[ROOMNAMELEN];
936         int msgs, new;
937
938         ret = imap_grabroom(roomname, parms[2]);
939         if (ret != 0) {
940                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
941                         parms[0]);
942                 return;
943         }
944
945         /*
946          * usergoto() formally takes us to the desired room.
947          */
948         if (IMAP->selected) {
949                 strcpy(savedroom, CC->room.QRname);
950         }
951         usergoto(roomname, 0, 0, &msgs, &new);
952
953         /* 
954          * Now make the API call to zap the room
955          */
956         if (CtdlForgetThisRoom() == 0) {
957                 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
958         }
959         else {
960                 cprintf("%s NO You may not unsubscribe from this folder.\r\n",
961                         parms[0]);
962         }
963
964         /*
965          * If another folder is selected, go back to that room so we can resume
966          * our happy day without violent explosions.
967          */
968         if (IMAP->selected) {
969                 usergoto(savedroom, 0, 0, &msgs, &new);
970         }
971 }
972
973
974
975 /*
976  * Implements the DELETE command
977  *
978  */
979 void imap_delete(int num_parms, char *parms[]) {
980         int ret;
981         char roomname[ROOMNAMELEN];
982         char savedroom[ROOMNAMELEN];
983         int msgs, new;
984
985         ret = imap_grabroom(roomname, parms[2]);
986         if (ret != 0) {
987                 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
988                         parms[0]);
989                 return;
990         }
991
992         /*
993          * usergoto() formally takes us to the desired room, happily returning
994          * the number of messages and number of new messages.  (If another
995          * folder is selected, save its name so we can return there!!!!!)
996          */
997         if (IMAP->selected) {
998                 strcpy(savedroom, CC->room.QRname);
999         }
1000         usergoto(roomname, 0, 0, &msgs, &new);
1001
1002         /*
1003          * Now delete the room.
1004          */
1005         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->room)) {
1006                 cprintf("%s OK DELETE completed\r\n", parms[0]);
1007                 delete_room(&CC->room);
1008         }
1009         else {
1010                 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
1011         }
1012
1013         /*
1014          * If another folder is selected, go back to that room so we can resume
1015          * our happy day without violent explosions.
1016          */
1017         if (IMAP->selected) {
1018                 usergoto(savedroom, 0, 0, &msgs, &new);
1019         }
1020 }
1021
1022
1023 /*
1024  * Back end function for imap_rename()
1025  */
1026 void imap_rename_backend(struct ctdlroom *qrbuf, void *data) {
1027         char foldername[SIZ];
1028         char newfoldername[SIZ];
1029         char newroomname[ROOMNAMELEN];
1030         int newfloor = 0;
1031         struct irl *irlp = NULL;        /* scratch pointer */
1032         struct irlparms *irlparms;
1033
1034         irlparms = (struct irlparms *)data;
1035         imap_mailboxname(foldername, sizeof foldername, qrbuf);
1036
1037         /* Rename subfolders */
1038         if ( (!strncasecmp(foldername, irlparms->oldname,
1039            strlen(irlparms->oldname))
1040            && (foldername[strlen(irlparms->oldname)] == '|')) ) {
1041
1042                 sprintf(newfoldername, "%s|%s",
1043                         irlparms->newname,
1044                         &foldername[strlen(irlparms->oldname)+1]
1045                 );
1046
1047                 newfloor = imap_roomname(newroomname,
1048                         sizeof newroomname, newfoldername) & 0xFF;
1049
1050                 irlp = (struct irl *) mallok(sizeof(struct irl));
1051                 strcpy(irlp->irl_newroom, newroomname);
1052                 strcpy(irlp->irl_oldroom, qrbuf->QRname);
1053                 irlp->irl_newfloor = newfloor;
1054                 irlp->next = *(irlparms->irl);
1055                 *(irlparms->irl) = irlp;
1056         }
1057 }
1058         
1059
1060 /*
1061  * Implements the RENAME command
1062  *
1063  */
1064 void imap_rename(int num_parms, char *parms[]) {
1065         char old_room[ROOMNAMELEN];
1066         char new_room[ROOMNAMELEN];
1067         int oldr, newr;
1068         int new_floor;
1069         int r;
1070         struct irl *irl = NULL;         /* the list */
1071         struct irl *irlp = NULL;        /* scratch pointer */
1072         struct irlparms irlparms;
1073
1074         if (strchr(parms[3], '\\') != NULL) {
1075                 cprintf("%s NO Invalid character in folder name\r\n", parms[0]);
1076                 return;
1077         }
1078
1079         oldr = imap_roomname(old_room, sizeof old_room, parms[2]);
1080         newr = imap_roomname(new_room, sizeof new_room, parms[3]);
1081         new_floor = (newr & 0xFF);
1082
1083         r = CtdlRenameRoom(old_room, new_room, new_floor);
1084
1085         if (r == crr_room_not_found) {
1086                 cprintf("%s NO Could not locate this folder\r\n", parms[0]);
1087                 return;
1088         }
1089         if (r == crr_already_exists) {
1090                 cprintf("%s '%s' already exists.\r\n", parms[0], parms[2]);
1091                 return;
1092         }
1093         if (r == crr_noneditable) {
1094                 cprintf("%s This folder is not editable.\r\n", parms[0]);
1095                 return;
1096         }
1097         if (r == crr_invalid_floor) {
1098                 cprintf("%s Folder root does not exist.\r\n", parms[0]);
1099                 return;
1100         }
1101         if (r == crr_access_denied) {
1102                 cprintf("%s You do not have permission to edit "
1103                         "this folder.\r\n", parms[0]);
1104                 return;
1105         }
1106         if (r != crr_ok) {
1107                 cprintf("%s NO Rename failed - undefined error %d\r\n",
1108                         parms[0], r);
1109                 return;
1110         }
1111
1112
1113         /* If this is the INBOX, then RFC2060 says we have to just move the
1114          * contents.  In a Citadel environment it's easier to rename the room
1115          * (already did that) and create a new inbox.
1116          */
1117         if (!strcasecmp(parms[2], "INBOX")) {
1118                 create_room(MAILROOM, 4, "", 0, 1, 0);
1119         }
1120
1121         /* Otherwise, do the subfolders.  Build a list of rooms to rename... */
1122         else {
1123                 irlparms.oldname = parms[2];
1124                 irlparms.newname = parms[3];
1125                 irlparms.irl = &irl;
1126                 ForEachRoom(imap_rename_backend, (void *)&irlparms);
1127
1128                 /* ... and now rename them. */
1129                 while (irl != NULL) {
1130                         r = CtdlRenameRoom(irl->irl_oldroom,
1131                                 irl->irl_newroom, irl->irl_newfloor);
1132                         if (r != crr_ok) {
1133                                 /* FIXME handle error returns better */
1134                                 lprintf(5, "CtdlRenameRoom() error %d\n", r);
1135                         }
1136                         irlp = irl;
1137                         irl = irl->next;
1138                         phree(irlp);
1139                 }
1140         }
1141
1142         cprintf("%s OK RENAME completed\r\n", parms[0]);
1143 }
1144
1145
1146
1147
1148 /* 
1149  * Main command loop for IMAP sessions.
1150  */
1151 void imap_command_loop(void) {
1152         char cmdbuf[SIZ];
1153         char *parms[SIZ];
1154         int num_parms;
1155
1156         time(&CC->lastcmd);
1157         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
1158         if (client_gets(cmdbuf) < 1) {
1159                 lprintf(3, "IMAP socket is broken.  Ending session.\r\n");
1160                 CC->kill_me = 1;
1161                 return;
1162         }
1163
1164         lprintf(5, "IMAP: %s\r\n", cmdbuf);
1165         while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
1166
1167
1168         /* strip off l/t whitespace and CRLF */
1169         if (cmdbuf[strlen(cmdbuf)-1]=='\n') cmdbuf[strlen(cmdbuf)-1]=0;
1170         if (cmdbuf[strlen(cmdbuf)-1]=='\r') cmdbuf[strlen(cmdbuf)-1]=0;
1171         striplt(cmdbuf);
1172
1173         /* If we're in the middle of a multi-line command, handle that */
1174         if (IMAP->authstate == imap_as_expecting_username) {
1175                 imap_auth_login_user(cmdbuf);
1176                 return;
1177         }
1178         if (IMAP->authstate == imap_as_expecting_password) {
1179                 imap_auth_login_pass(cmdbuf);
1180                 return;
1181         }
1182
1183
1184         /* Ok, at this point we're in normal command mode.  The first thing
1185          * we do is print any incoming pages (yeah! we really do!)
1186          */
1187         imap_print_express_messages();
1188
1189         /*
1190          * Before processing the command that was just entered... if we happen
1191          * to have a folder selected, we'd like to rescan that folder for new
1192          * messages, and for deletions/changes of existing messages.  This
1193          * could probably be optimized somehow, but IMAP sucks...
1194          */
1195         if (IMAP->selected) {
1196                 imap_rescan_msgids();
1197         }
1198
1199         /* Now for the command set. */
1200
1201         /* Grab the tag, command, and parameters.  Check syntax. */
1202         num_parms = imap_parameterize(parms, cmdbuf);
1203         if (num_parms < 2) {
1204                 cprintf("BAD syntax error\r\n");
1205         }
1206
1207         /* The commands below may be executed in any state */
1208
1209         else if ( (!strcasecmp(parms[1], "NOOP"))
1210            || (!strcasecmp(parms[1], "CHECK")) ) {
1211                 cprintf("%s OK This command successfully did nothing.\r\n",
1212                         parms[0]);
1213         }
1214
1215         else if (!strcasecmp(parms[1], "LOGOUT")) {
1216                 imap_do_expunge();      /* yes, we auto-expunge */
1217                 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
1218                 cprintf("%s OK thank you for using Citadel IMAP\r\n", parms[0]);
1219                 CC->kill_me = 1;
1220                 return;
1221         }
1222
1223         else if (!strcasecmp(parms[1], "LOGIN")) {
1224                 imap_login(num_parms, parms);
1225         }
1226
1227         else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
1228                 imap_authenticate(num_parms, parms);
1229         }
1230
1231         else if (!strcasecmp(parms[1], "CAPABILITY")) {
1232                 imap_capability(num_parms, parms);
1233         }
1234
1235 #ifdef HAVE_OPENSSL_XXX /* temporarily disabled due to bugs */
1236         else if (!strcasecmp(parms[1], "STARTTLS")) {
1237                 imap_starttls(num_parms, parms);
1238         }
1239 #endif
1240
1241         else if (!CC->logged_in) {
1242                 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1243         }
1244
1245         /* The commans below require a logged-in state */
1246
1247         else if (!strcasecmp(parms[1], "SELECT")) {
1248                 imap_select(num_parms, parms);
1249         }
1250
1251         else if (!strcasecmp(parms[1], "EXAMINE")) {
1252                 imap_select(num_parms, parms);
1253         }
1254
1255         else if (!strcasecmp(parms[1], "LSUB")) {
1256                 imap_lsub(num_parms, parms);
1257         }
1258
1259         else if (!strcasecmp(parms[1], "LIST")) {
1260                 imap_list(num_parms, parms);
1261         }
1262
1263         else if (!strcasecmp(parms[1], "CREATE")) {
1264                 imap_create(num_parms, parms);
1265         }
1266
1267         else if (!strcasecmp(parms[1], "DELETE")) {
1268                 imap_delete(num_parms, parms);
1269         }
1270
1271         else if (!strcasecmp(parms[1], "RENAME")) {
1272                 imap_rename(num_parms, parms);
1273         }
1274
1275         else if (!strcasecmp(parms[1], "STATUS")) {
1276                 imap_status(num_parms, parms);
1277         }
1278
1279         else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1280                 imap_subscribe(num_parms, parms);
1281         }
1282
1283         else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1284                 imap_unsubscribe(num_parms, parms);
1285         }
1286
1287         else if (!strcasecmp(parms[1], "APPEND")) {
1288                 imap_append(num_parms, parms);
1289         }
1290
1291         else if (IMAP->selected == 0) {
1292                 cprintf("%s BAD no folder selected\r\n", parms[0]);
1293         }
1294
1295         /* The commands below require the SELECT state on a mailbox */
1296
1297         else if (!strcasecmp(parms[1], "FETCH")) {
1298                 imap_fetch(num_parms, parms);
1299         }
1300
1301         else if ( (!strcasecmp(parms[1], "UID"))
1302                 && (!strcasecmp(parms[2], "FETCH")) ) {
1303                 imap_uidfetch(num_parms, parms);
1304         }
1305
1306         else if (!strcasecmp(parms[1], "SEARCH")) {
1307                 imap_search(num_parms, parms);
1308         }
1309
1310         else if ( (!strcasecmp(parms[1], "UID"))
1311                 && (!strcasecmp(parms[2], "SEARCH")) ) {
1312                 imap_uidsearch(num_parms, parms);
1313         }
1314
1315         else if (!strcasecmp(parms[1], "STORE")) {
1316                 imap_store(num_parms, parms);
1317         }
1318
1319         else if ( (!strcasecmp(parms[1], "UID"))
1320                 && (!strcasecmp(parms[2], "STORE")) ) {
1321                 imap_uidstore(num_parms, parms);
1322         }
1323
1324         else if (!strcasecmp(parms[1], "COPY")) {
1325                 imap_copy(num_parms, parms);
1326         }
1327
1328         else if ( (!strcasecmp(parms[1], "UID"))
1329                 && (!strcasecmp(parms[2], "COPY")) ) {
1330                 imap_uidcopy(num_parms, parms);
1331         }
1332
1333         else if (!strcasecmp(parms[1], "EXPUNGE")) {
1334                 imap_expunge(num_parms, parms);
1335         }
1336
1337         else if (!strcasecmp(parms[1], "CLOSE")) {
1338                 imap_close(num_parms, parms);
1339         }
1340
1341         /* End of commands.  If we get here, the command is either invalid
1342          * or unimplemented.
1343          */
1344
1345         else {
1346                 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1347         }
1348
1349         /* If the client transmitted a message we can free it now */
1350         imap_free_transmitted_message();
1351 }
1352
1353
1354
1355 /*
1356  * This function is called to register the IMAP extension with Citadel.
1357  */
1358 char *serv_imap_init(void)
1359 {
1360         CtdlRegisterServiceHook(config.c_imap_port,
1361                                 NULL,
1362                                 imap_greeting,
1363                                 imap_command_loop);
1364         CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1365         return "$Id$";
1366 }