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