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