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