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