* Renamed "struct user" to "struct ctdluser"
[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: this is a workable implementation, but it could use some
9  * additional tweaking.  Some commands may be implemented incompletely.  The
10  * 'SEARCH' command is not implemented at all.
11  *
12  * WARNING: Mark Crispin is an idiot.  IMAP is the most brain-damaged protocol
13  * you will ever have the profound lack of pleasure to encounter.
14  */
15
16 #include "sysdep.h"
17 #include <stdlib.h>
18 #include <unistd.h>
19 #include <stdio.h>
20 #include <fcntl.h>
21 #include <signal.h>
22 #include <pwd.h>
23 #include <errno.h>
24 #include <sys/types.h>
25
26 #if TIME_WITH_SYS_TIME
27 # include <sys/time.h>
28 # include <time.h>
29 #else
30 # if HAVE_SYS_TIME_H
31 #  include <sys/time.h>
32 # else
33 #  include <time.h>
34 # endif
35 #endif
36
37 #include <sys/wait.h>
38 #include <ctype.h>
39 #include <string.h>
40 #include <limits.h>
41
42 #ifdef HAVE_OPENSSL
43 #include <openssl/ssl.h>
44 #include <openssl/err.h>
45 #include <openssl/rand.h>
46 #endif
47
48 #include "citadel.h"
49 #include "server.h"
50 #include "sysdep_decls.h"
51 #include "citserver.h"
52 #include "support.h"
53 #include "config.h"
54 #include "serv_extensions.h"
55 #include "room_ops.h"
56 #include "user_ops.h"
57 #include "policy.h"
58 #include "database.h"
59 #include "msgbase.h"
60 #include "tools.h"
61 #include "internet_addressing.h"
62 #include "serv_imap.h"
63 #include "imap_tools.h"
64 #include "imap_fetch.h"
65 #include "imap_search.h"
66 #include "imap_store.h"
67 #include "imap_misc.h"
68
69 #ifdef HAVE_OPENSSL
70 #include "serv_crypto.h"
71 #endif
72
73 /* imap_rename() uses this struct containing list of rooms to rename */
74 struct irl {
75         struct irl *next;
76         char irl_oldroom[ROOMNAMELEN];
77         char irl_newroom[ROOMNAMELEN];
78         int irl_newfloor;
79 };
80
81 /* Data which is passed between imap_rename() and imap_rename_backend() */
82 struct irlparms { 
83         char *oldname;
84         char *newname;
85         struct irl **irl;
86 };
87
88 long SYM_IMAP;
89
90
91 /*
92  * If there is a message ID map in memory, free it
93  */
94 void imap_free_msgids(void) {
95         if (IMAP->msgids != NULL) {
96                 phree(IMAP->msgids);
97                 IMAP->msgids = NULL;
98                 IMAP->num_msgs = 0;
99         }
100         if (IMAP->flags != NULL) {
101                 phree(IMAP->flags);
102                 IMAP->flags = NULL;
103         }
104 }
105
106
107 /*
108  * If there is a transmitted message in memory, free it
109  */
110 void imap_free_transmitted_message(void) {
111         if (IMAP->transmitted_message != NULL) {
112                 phree(IMAP->transmitted_message);
113                 IMAP->transmitted_message = NULL;
114                 IMAP->transmitted_length = 0;
115         }
116 }
117
118
119 /*
120  * Set the \\Seen flag for messages which aren't new
121  */
122 void imap_set_seen_flags(void) {
123         struct visit vbuf;
124         int i;
125
126         CtdlGetRelationship(&vbuf, &CC->user, &CC->room);
127         if (IMAP->num_msgs > 0) {
128                 for (i=0; i<IMAP->num_msgs; ++i) {
129                         if (is_msg_in_mset(vbuf.v_seen, IMAP->msgids[i])) {
130                                 IMAP->flags[i] |= IMAP_SEEN;
131                         }
132                 }
133         }
134 }
135
136
137
138
139 /*
140  * Back end for imap_load_msgids()
141  *
142  * Optimization: instead of calling realloc() to add each message, we
143  * allocate space in the list for REALLOC_INCREMENT messages at a time.  This
144  * allows the mapping to proceed much faster.
145  */
146 void imap_add_single_msgid(long msgnum, void *userdata) {
147         
148         IMAP->num_msgs = IMAP->num_msgs + 1;
149         if (IMAP->msgids == NULL) {
150                 IMAP->msgids = mallok(IMAP->num_msgs * sizeof(long)
151                                         * REALLOC_INCREMENT);
152         }
153         else if (IMAP->num_msgs % REALLOC_INCREMENT == 0) {
154                 IMAP->msgids = reallok(IMAP->msgids,
155                         (IMAP->num_msgs + REALLOC_INCREMENT) * sizeof(long));
156         }
157         if (IMAP->flags == NULL) {
158                 IMAP->flags = mallok(IMAP->num_msgs * sizeof(long)
159                                         * REALLOC_INCREMENT);
160         }
161         else if (IMAP->num_msgs % REALLOC_INCREMENT == 0) {
162                 IMAP->flags = reallok(IMAP->flags,
163                         (IMAP->num_msgs + REALLOC_INCREMENT) * sizeof(long));
164         }
165         IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
166         IMAP->flags[IMAP->num_msgs - 1] = 0;
167 }
168
169
170
171 /*
172  * Set up a message ID map for the current room (folder)
173  */
174 void imap_load_msgids(void) {
175          
176         if (IMAP->selected == 0) {
177                 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
178                 return;
179         }
180
181         imap_free_msgids();     /* If there was already a map, free it */
182
183         CtdlForEachMessage(MSGS_ALL, 0L, NULL, NULL,
184                 imap_add_single_msgid, NULL);
185
186         imap_set_seen_flags();
187         lprintf(9, "imap_load_msgids() mapped %d messages\n", IMAP->num_msgs);
188 }
189
190
191 /*
192  * Re-scan the selected room (folder) and see if it's been changed at all
193  */
194 void imap_rescan_msgids(void) {
195
196         int original_num_msgs = 0;
197         long original_highest = 0L;
198         int i, j;
199         int message_still_exists;
200         struct cdbdata *cdbfr;
201         long *msglist = NULL;
202         int num_msgs = 0;
203
204
205         if (IMAP->selected == 0) {
206                 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
207                 return;
208         }
209
210         /* Load the *current* message list from disk, so we can compare it
211          * to what we have in memory.
212          */
213         cdbfr = cdb_fetch(CDB_MSGLISTS, &CC->room.QRnumber, sizeof(long));
214         if (cdbfr != NULL) {
215                 msglist = mallok(cdbfr->len);
216                 memcpy(msglist, cdbfr->ptr, cdbfr->len);
217                 num_msgs = cdbfr->len / sizeof(long);
218                 cdb_free(cdbfr);
219         }
220         else {
221                 num_msgs = 0;
222         }
223
224         /*
225          * Check to see if any of the messages we know about have been expunged
226          */
227         if (IMAP->num_msgs > 0)
228          for (i=0; i<IMAP->num_msgs; ++i) {
229
230                 message_still_exists = 0;
231                 if (num_msgs > 0) for (j = 0; j < num_msgs; ++j) {
232                         if (msglist[j] == IMAP->msgids[i]) {
233                                 message_still_exists = 1;
234                         }
235                 }
236
237                 if (message_still_exists == 0) {
238                         cprintf("* %d EXPUNGE\r\n", i+1);
239
240                         /* Here's some nice stupid nonsense.  When a message
241                          * is expunged, we have to slide all the existing
242                          * messages up in the message array.
243                          */
244                         --IMAP->num_msgs;
245                         memcpy(&IMAP->msgids[i], &IMAP->msgids[i+1],
246                                 (sizeof(long)*(IMAP->num_msgs-i)) );
247                         memcpy(&IMAP->flags[i], &IMAP->flags[i+1],
248                                 (sizeof(long)*(IMAP->num_msgs-i)) );
249
250                         --i;
251                 }
252
253         }
254
255         /*
256          * Remember how many messages were here before we re-scanned.
257          */
258         original_num_msgs = IMAP->num_msgs;
259         if (IMAP->num_msgs > 0) {
260                 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
261         }
262         else {
263                 original_highest = 0L;
264         }
265
266         /*
267          * Now peruse the room for *new* messages only.
268          */
269         if (num_msgs > 0) for (j=0; j<num_msgs; ++j) {
270                 if (msglist[j] > original_highest) {
271                         imap_add_single_msgid(msglist[j], NULL);
272                 }
273         }
274         imap_set_seen_flags();
275
276         /*
277          * If new messages have arrived, tell the client about them.
278          */
279         if (IMAP->num_msgs > original_num_msgs) {
280                 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
281         }
282
283         if (num_msgs != 0) phree(msglist);
284 }
285
286
287
288
289
290
291
292 /*
293  * This cleanup function blows away the temporary memory and files used by
294  * the IMAP server.
295  */
296 void imap_cleanup_function(void) {
297
298         /* Don't do this stuff if this is not a IMAP session! */
299         if (CC->h_command_function != imap_command_loop) return;
300
301         lprintf(9, "Performing IMAP cleanup hook\n");
302         imap_free_msgids();
303         imap_free_transmitted_message();
304         lprintf(9, "Finished IMAP cleanup hook\n");
305 }
306
307
308
309 /*
310  * Here's where our IMAP session begins its happy day.
311  */
312 void imap_greeting(void) {
313
314         strcpy(CC->cs_clientname, "IMAP session");
315         CtdlAllocUserData(SYM_IMAP, sizeof(struct citimap));
316         IMAP->authstate = imap_as_normal;
317
318         cprintf("* OK %s Citadel/UX IMAP4rev1 server ready\r\n",
319                 config.c_fqdn);
320 }
321
322
323 /*
324  * implements the LOGIN command (ordinary username/password login)
325  */
326 void imap_login(int num_parms, char *parms[]) {
327         if (CtdlLoginExistingUser(parms[2]) == login_ok) {
328                 if (CtdlTryPassword(parms[3]) == pass_ok) {
329                         cprintf("%s OK login successful\r\n", parms[0]);
330                         return;
331                 }
332         }
333
334         cprintf("%s BAD Login incorrect\r\n", parms[0]);
335 }
336
337
338 /*
339  * Implements the AUTHENTICATE command
340  */
341 void imap_authenticate(int num_parms, char *parms[]) {
342         char buf[SIZ];
343
344         if (num_parms != 3) {
345                 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
346                 return;
347         }
348
349         if (!strcasecmp(parms[2], "LOGIN")) {
350                 CtdlEncodeBase64(buf, "Username:", 9);
351                 cprintf("+ %s\r\n", buf);
352                 IMAP->authstate = imap_as_expecting_username;
353                 strcpy(IMAP->authseq, parms[0]);
354                 return;
355         }
356
357         else {
358                 cprintf("%s NO AUTHENTICATE %s failed\r\n",
359                         parms[0], parms[1]);
360         }
361 }
362
363 void imap_auth_login_user(char *cmd) {
364         char buf[SIZ];
365
366         CtdlDecodeBase64(buf, cmd, SIZ);
367         CtdlLoginExistingUser(buf);
368         CtdlEncodeBase64(buf, "Password:", 9);
369         cprintf("+ %s\r\n", buf);
370         IMAP->authstate = imap_as_expecting_password;
371         return;
372 }
373
374 void imap_auth_login_pass(char *cmd) {
375         char buf[SIZ];
376
377         CtdlDecodeBase64(buf, cmd, SIZ);
378         if (CtdlTryPassword(buf) == pass_ok) {
379                 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
380         }
381         else {
382                 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
383         }
384         IMAP->authstate = imap_as_normal;
385         return;
386 }
387
388
389
390 /*
391  * implements the CAPABILITY command
392  */
393 void imap_capability(int num_parms, char *parms[]) {
394         cprintf("* CAPABILITY IMAP4 IMAP4REV1 AUTH=LOGIN");
395 #ifdef HAVE_OPENSSL
396         cprintf(" STARTTLS");
397 #endif
398         cprintf("\r\n");
399         cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
400 }
401
402
403 /*
404  * implements the STARTTLS command
405  */
406 #ifdef HAVE_OPENSSL
407 void imap_starttls(int num_parms, char *parms[]) {
408         int retval, bits, alg_bits;
409
410         if (!ssl_ctx) {
411                 cprintf("%s NO No SSL_CTX available\r\n", parms[0]);
412                 return;
413         }
414         if (!(CC->ssl = SSL_new(ssl_ctx))) {
415                 lprintf(2, "SSL_new failed: %s\n",
416                                 ERR_reason_error_string(ERR_peek_error()));
417                 cprintf("%s NO SSL_new: %s\r\n", parms[0],
418                                 ERR_reason_error_string(ERR_get_error()));
419                 return;
420         }
421         if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
422                 lprintf(2, "SSL_set_fd failed: %s\n",
423                                 ERR_reason_error_string(ERR_peek_error()));
424                 SSL_free(CC->ssl);
425                 CC->ssl = NULL;
426                 cprintf("%s NO SSL_set_fd: %s\r\n", parms[0],
427                                 ERR_reason_error_string(ERR_get_error()));
428                 return;
429         }
430         cprintf("%s OK begin TLS negotiation now\r\n", parms[0]);
431         retval = SSL_accept(CC->ssl);
432         if (retval < 1) {
433                 /*
434                  * Can't notify the client of an error here; they will
435                  * discover the problem at the SSL layer and should
436                  * revert to unencrypted communications.
437                  */
438                 long errval;
439
440                 errval = SSL_get_error(CC->ssl, retval);
441                 lprintf(2, "SSL_accept failed: %s\n",
442                                 ERR_reason_error_string(ERR_get_error()));
443                 SSL_free(CC->ssl);
444                 CC->ssl = NULL;
445                 return;
446         }
447         BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
448         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
449         lprintf(3, "SSL/TLS using %s on %s (%d of %d bits)\n",
450                         SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
451                         SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
452                         bits, alg_bits);
453         CC->redirect_ssl = 1;
454 }
455 #endif
456
457
458
459 /*
460  * implements the SELECT command
461  */
462 void imap_select(int num_parms, char *parms[]) {
463         char towhere[SIZ];
464         char augmented_roomname[ROOMNAMELEN];
465         int c = 0;
466         int ok = 0;
467         int ra = 0;
468         struct ctdlroom QRscratch;
469         int msgs, new;
470         int floornum;
471         int roomflags;
472         int i;
473
474         /* Convert the supplied folder name to a roomname */
475         i = imap_roomname(towhere, sizeof towhere, parms[2]);
476         if (i < 0) {
477                 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
478                 IMAP->selected = 0;
479                 return;
480         }
481         floornum = (i & 0x00ff);
482         roomflags = (i & 0xff00);
483
484         /* First try a regular match */
485         c = getroom(&QRscratch, towhere);
486
487         /* Then try a mailbox name match */
488         if (c != 0) {
489                 MailboxName(augmented_roomname, sizeof augmented_roomname,
490                             &CC->user, towhere);
491                 c = getroom(&QRscratch, augmented_roomname);
492                 if (c == 0)
493                         strcpy(towhere, augmented_roomname);
494         }
495
496         /* If the room exists, check security/access */
497         if (c == 0) {
498                 /* See if there is an existing user/room relationship */
499                 ra = CtdlRoomAccess(&QRscratch, &CC->user);
500
501                 /* normal clients have to pass through security */
502                 if (ra & UA_KNOWN) {
503                         ok = 1;
504                 }
505         }
506
507         /* Fail here if no such room */
508         if (!ok) {
509                 cprintf("%s NO ... no such room, or access denied\r\n",
510                         parms[0]);
511                 IMAP->selected = 0;
512                 return;
513         }
514
515         /*
516          * usergoto() formally takes us to the desired room, happily returning
517          * the number of messages and number of new messages.
518          */
519         memcpy(&CC->room, &QRscratch, sizeof(struct ctdlroom));
520         usergoto(NULL, 0, 0, &msgs, &new);
521         IMAP->selected = 1;
522
523         if (!strcasecmp(parms[1], "EXAMINE")) {
524                 IMAP->readonly = 1;
525         }
526         else {
527                 IMAP->readonly = 0;
528         }
529
530         imap_load_msgids();
531
532         /* FIXME ... much more info needs to be supplied here */
533         cprintf("* %d EXISTS\r\n", msgs);
534         cprintf("* %d RECENT\r\n", new);
535         cprintf("* FLAGS (\\Deleted \\Seen)\r\n");
536         cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen)] 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
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         SYM_IMAP = CtdlGetDynamicSymbol();
1349         CtdlRegisterServiceHook(config.c_imap_port,
1350                                 NULL,
1351                                 imap_greeting,
1352                                 imap_command_loop);
1353         CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1354         return "$Id$";
1355 }