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