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