]> code.citadel.org Git - citadel.git/blob - citadel/serv_imap.c
* Support nested folders in IMAP. We might want to change the delimiter.
[citadel.git] / citadel / serv_imap.c
1 /*
2  * $Id$ 
3  *
4  * IMAP server for the Citadel/UX system
5  * Copyright (C) 2000-2001 by Art Cancro and others.
6  * This code is released under the terms of the GNU General Public License.
7  *
8  * WARNING: this is an incomplete implementation.  It is now good enough to
9  * be usable with much of the popular IMAP client software available, but it
10  * is by no means perfect.  Some commands (particularly SEARCH and RENAME)
11  * are implemented either incompletely or not at all.
12  *
13  * WARNING: Mark Crispin is an idiot.  IMAP is the most brain-damaged protocol
14  * you will ever have the profound lack of pleasure to encounter.
15  * 
16  */
17
18 #include "sysdep.h"
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <stdio.h>
22 #include <fcntl.h>
23 #include <signal.h>
24 #include <pwd.h>
25 #include <errno.h>
26 #include <sys/types.h>
27
28 #if TIME_WITH_SYS_TIME
29 # include <sys/time.h>
30 # include <time.h>
31 #else
32 # if HAVE_SYS_TIME_H
33 #  include <sys/time.h>
34 # else
35 #  include <time.h>
36 # endif
37 #endif
38
39 #include <sys/wait.h>
40 #include <ctype.h>
41 #include <string.h>
42 #include <limits.h>
43 #include "citadel.h"
44 #include "server.h"
45 #include "sysdep_decls.h"
46 #include "citserver.h"
47 #include "support.h"
48 #include "config.h"
49 #include "dynloader.h"
50 #include "room_ops.h"
51 #include "user_ops.h"
52 #include "policy.h"
53 #include "database.h"
54 #include "msgbase.h"
55 #include "tools.h"
56 #include "internet_addressing.h"
57 #include "serv_imap.h"
58 #include "imap_tools.h"
59 #include "imap_fetch.h"
60 #include "imap_search.h"
61 #include "imap_store.h"
62 #include "imap_misc.h"
63
64
65 long SYM_IMAP;
66
67
68 /*
69  * If there is a message ID map in memory, free it
70  */
71 void imap_free_msgids(void) {
72         if (IMAP->msgids != NULL) {
73                 phree(IMAP->msgids);
74                 IMAP->msgids = NULL;
75                 IMAP->num_msgs = 0;
76         }
77         if (IMAP->flags != NULL) {
78                 phree(IMAP->flags);
79                 IMAP->flags = NULL;
80         }
81 }
82
83
84 /*
85  * If there is a transmitted message in memory, free it
86  */
87 void imap_free_transmitted_message(void) {
88         if (IMAP->transmitted_message != NULL) {
89                 phree(IMAP->transmitted_message);
90                 IMAP->transmitted_message = NULL;
91                 IMAP->transmitted_length = 0;
92         }
93 }
94
95
96 /*
97  * Set the \\Seen flag for messages which aren't new
98  */
99 void imap_set_seen_flags(void) {
100         struct visit vbuf;
101         int i;
102
103         CtdlGetRelationship(&vbuf, &CC->usersupp, &CC->quickroom);
104         if (IMAP->num_msgs > 0) {
105                 for (i=0; i<IMAP->num_msgs; ++i) {
106                         if (is_msg_in_mset(vbuf.v_seen, IMAP->msgids[i])) {
107                                 IMAP->flags[i] |= IMAP_SEEN;
108                         }
109                 }
110         }
111 }
112
113
114
115
116 /*
117  * Back end for imap_load_msgids()
118  *
119  * Optimization: instead of calling realloc() to add each message, we
120  * allocate space in the list for REALLOC_INCREMENT messages at a time.  This
121  * allows the mapping to proceed much faster.
122  */
123 void imap_add_single_msgid(long msgnum, void *userdata) {
124         
125         IMAP->num_msgs = IMAP->num_msgs + 1;
126         if (IMAP->msgids == NULL) {
127                 IMAP->msgids = mallok(IMAP->num_msgs * sizeof(long)
128                                         * REALLOC_INCREMENT);
129         }
130         else if (IMAP->num_msgs % REALLOC_INCREMENT == 0) {
131                 IMAP->msgids = reallok(IMAP->msgids,
132                         (IMAP->num_msgs + REALLOC_INCREMENT) * sizeof(long));
133         }
134         if (IMAP->flags == NULL) {
135                 IMAP->flags = mallok(IMAP->num_msgs * sizeof(long)
136                                         * REALLOC_INCREMENT);
137         }
138         else if (IMAP->num_msgs % REALLOC_INCREMENT == 0) {
139                 IMAP->flags = reallok(IMAP->flags,
140                         (IMAP->num_msgs + REALLOC_INCREMENT) * sizeof(long));
141         }
142         IMAP->msgids[IMAP->num_msgs - 1] = msgnum;
143         IMAP->flags[IMAP->num_msgs - 1] = 0;
144 }
145
146
147
148 /*
149  * Set up a message ID map for the current room (folder)
150  */
151 void imap_load_msgids(void) {
152          
153         if (IMAP->selected == 0) {
154                 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
155                 return;
156         }
157
158         imap_free_msgids();     /* If there was already a map, free it */
159
160         CtdlForEachMessage(MSGS_ALL, 0L, (-63), NULL, NULL,
161                 imap_add_single_msgid, NULL);
162
163         imap_set_seen_flags();
164         lprintf(9, "imap_load_msgids() mapped %d messages\n", IMAP->num_msgs);
165 }
166
167
168 /*
169  * Re-scan the selected room (folder) and see if it's been changed at all
170  */
171 void imap_rescan_msgids(void) {
172
173         int original_num_msgs = 0;
174         long original_highest = 0L;
175         int i;
176         int count;
177
178         if (IMAP->selected == 0) {
179                 lprintf(5, "imap_load_msgids() can't run; no room selected\n");
180                 return;
181         }
182
183
184         /*
185          * Check to see if any of the messages we know about have been expunged
186          */
187         if (IMAP->num_msgs > 0)
188          for (i=0; i<IMAP->num_msgs; ++i) {
189
190                 count = CtdlForEachMessage(MSGS_EQ, IMAP->msgids[i],
191                         (-63), NULL, NULL, NULL, NULL);
192
193                 if (count == 0) {
194                         cprintf("* %d EXPUNGE\r\n", i+1);
195
196                         /* Here's some nice stupid nonsense.  When a message
197                          * is expunged, we have to slide all the existing
198                          * messages up in the message array.
199                          */
200                         --IMAP->num_msgs;
201                         memcpy(&IMAP->msgids[i], &IMAP->msgids[i+1],
202                                 (sizeof(long)*(IMAP->num_msgs-i)) );
203                         memcpy(&IMAP->flags[i], &IMAP->flags[i+1],
204                                 (sizeof(long)*(IMAP->num_msgs-i)) );
205
206                         --i;
207                 }
208
209         }
210
211         /*
212          * Remember how many messages were here before we re-scanned.
213          */
214         original_num_msgs = IMAP->num_msgs;
215         if (IMAP->num_msgs > 0) {
216                 original_highest = IMAP->msgids[IMAP->num_msgs - 1];
217         }
218         else {
219                 original_highest = 0L;
220         }
221
222         /*
223          * Now peruse the room for *new* messages only.
224          */
225         CtdlForEachMessage(MSGS_GT, original_highest, (-63), NULL, NULL,
226                 imap_add_single_msgid, NULL);
227
228         imap_set_seen_flags();
229
230         /*
231          * If new messages have arrived, tell the client about them.
232          */
233         if (IMAP->num_msgs > original_num_msgs) {
234                 cprintf("* %d EXISTS\r\n", IMAP->num_msgs);
235         }
236
237 }
238
239
240
241
242
243
244
245 /*
246  * This cleanup function blows away the temporary memory and files used by
247  * the IMAP server.
248  */
249 void imap_cleanup_function(void) {
250
251         /* Don't do this stuff if this is not a IMAP session! */
252         if (CC->h_command_function != imap_command_loop) return;
253
254         lprintf(9, "Performing IMAP cleanup hook\n");
255         imap_free_msgids();
256         imap_free_transmitted_message();
257         lprintf(9, "Finished IMAP cleanup hook\n");
258 }
259
260
261
262 /*
263  * Here's where our IMAP session begins its happy day.
264  */
265 void imap_greeting(void) {
266
267         strcpy(CC->cs_clientname, "IMAP session");
268         CtdlAllocUserData(SYM_IMAP, sizeof(struct citimap));
269         IMAP->authstate = imap_as_normal;
270
271         cprintf("* OK %s Citadel/UX IMAP4rev1 server ready\r\n",
272                 config.c_fqdn);
273 }
274
275
276 /*
277  * implements the LOGIN command (ordinary username/password login)
278  */
279 void imap_login(int num_parms, char *parms[]) {
280         if (CtdlLoginExistingUser(parms[2]) == login_ok) {
281                 if (CtdlTryPassword(parms[3]) == pass_ok) {
282                         cprintf("%s OK login successful\r\n", parms[0]);
283                         return;
284                 }
285         }
286
287         cprintf("%s BAD Login incorrect\r\n", parms[0]);
288 }
289
290
291 /*
292  * Implements the AUTHENTICATE command
293  */
294 void imap_authenticate(int num_parms, char *parms[]) {
295         char buf[SIZ];
296
297         if (num_parms != 3) {
298                 cprintf("%s BAD incorrect number of parameters\r\n", parms[0]);
299                 return;
300         }
301
302         if (!strcasecmp(parms[2], "LOGIN")) {
303                 encode_base64(buf, "Username:");
304                 cprintf("+ %s\r\n", buf);
305                 IMAP->authstate = imap_as_expecting_username;
306                 strcpy(IMAP->authseq, parms[0]);
307                 return;
308         }
309
310         else {
311                 cprintf("%s NO AUTHENTICATE %s failed\r\n",
312                         parms[0], parms[1]);
313         }
314 }
315
316 void imap_auth_login_user(char *cmd) {
317         char buf[SIZ];
318
319         decode_base64(buf, cmd, SIZ);
320         CtdlLoginExistingUser(buf);
321         encode_base64(buf, "Password:");
322         cprintf("+ %s\r\n", buf);
323         IMAP->authstate = imap_as_expecting_password;
324         return;
325 }
326
327 void imap_auth_login_pass(char *cmd) {
328         char buf[SIZ];
329
330         decode_base64(buf, cmd, SIZ);
331         if (CtdlTryPassword(buf) == pass_ok) {
332                 cprintf("%s OK authentication succeeded\r\n", IMAP->authseq);
333         }
334         else {
335                 cprintf("%s NO authentication failed\r\n", IMAP->authseq);
336         }
337         IMAP->authstate = imap_as_normal;
338         return;
339 }
340
341
342
343 /*
344  * implements the CAPABILITY command
345  */
346 void imap_capability(int num_parms, char *parms[]) {
347         cprintf("* CAPABILITY IMAP4 IMAP4REV1 AUTH=LOGIN\r\n");
348         cprintf("%s OK CAPABILITY completed\r\n", parms[0]);
349 }
350
351
352
353
354
355 /*
356  * implements the SELECT command
357  */
358 void imap_select(int num_parms, char *parms[]) {
359         char towhere[SIZ];
360         char augmented_roomname[ROOMNAMELEN];
361         int c = 0;
362         int ok = 0;
363         int ra = 0;
364         struct quickroom QRscratch;
365         int msgs, new;
366         int floornum;
367         int roomflags;
368         int i;
369
370         /* Convert the supplied folder name to a roomname */
371         i = imap_roomname(towhere, sizeof towhere, parms[2]);
372         if (i < 0) {
373                 cprintf("%s NO Invalid mailbox name.\r\n", parms[0]);
374                 IMAP->selected = 0;
375                 return;
376         }
377         floornum = (i & 0x00ff);
378         roomflags = (i & 0xff00);
379
380         /* First try a regular match */
381         c = getroom(&QRscratch, towhere);
382
383         /* Then try a mailbox name match */
384         if (c != 0) {
385                 MailboxName(augmented_roomname, sizeof augmented_roomname,
386                             &CC->usersupp, towhere);
387                 c = getroom(&QRscratch, augmented_roomname);
388                 if (c == 0)
389                         strcpy(towhere, augmented_roomname);
390         }
391
392         /* If the room exists, check security/access */
393         if (c == 0) {
394                 /* See if there is an existing user/room relationship */
395                 ra = CtdlRoomAccess(&QRscratch, &CC->usersupp);
396
397                 /* normal clients have to pass through security */
398                 if (ra & UA_KNOWN) {
399                         ok = 1;
400                 }
401         }
402
403         /* Fail here if no such room */
404         if (!ok) {
405                 cprintf("%s NO ... no such room, or access denied\r\n",
406                         parms[0]);
407                 IMAP->selected = 0;
408                 return;
409         }
410
411         /*
412          * usergoto() formally takes us to the desired room, happily returning
413          * the number of messages and number of new messages.
414          */
415         usergoto(QRscratch.QRname, 0, &msgs, &new);
416         IMAP->selected = 1;
417
418         if (!strcasecmp(parms[1], "EXAMINE")) {
419                 IMAP->readonly = 1;
420         }
421         else {
422                 IMAP->readonly = 0;
423         }
424
425         imap_load_msgids();
426
427         /* FIXME ... much more info needs to be supplied here */
428         cprintf("* %d EXISTS\r\n", msgs);
429         cprintf("* %d RECENT\r\n", new);
430         cprintf("* FLAGS (\\Deleted \\Seen)\r\n");
431         cprintf("* OK [PERMANENTFLAGS (\\Deleted \\Seen)] permanent flags\r\n");
432         cprintf("* OK [UIDVALIDITY 0] UIDs valid\r\n");
433         cprintf("%s OK [%s] %s completed\r\n",
434                 parms[0],
435                 (IMAP->readonly ? "READ-ONLY" : "READ-WRITE"),
436                 parms[1]);
437 }
438
439
440
441 /*
442  * does the real work for expunge
443  */
444 int imap_do_expunge(void) {
445         int i;
446         int num_expunged = 0;
447
448         if (IMAP->num_msgs > 0) for (i=0; i<IMAP->num_msgs; ++i) {
449                 if (IMAP->flags[i] & IMAP_DELETED) {
450                         CtdlDeleteMessages(CC->quickroom.QRname,
451                                         IMAP->msgids[i], "");
452                         ++num_expunged;
453                 }
454         }
455
456         if (num_expunged > 0) {
457                 imap_rescan_msgids();
458         }
459
460         return(num_expunged);
461 }
462
463
464 /*
465  * implements the EXPUNGE command syntax
466  */
467 void imap_expunge(int num_parms, char *parms[]) {
468         int num_expunged = 0;
469         imap_do_expunge();
470         cprintf("%s OK expunged %d messages.\r\n", parms[0], num_expunged);
471 }
472
473
474 /*
475  * implements the CLOSE command
476  */
477 void imap_close(int num_parms, char *parms[]) {
478
479         /* Yes, we always expunge on close. */
480         imap_do_expunge();
481
482         IMAP->selected = 0;
483         IMAP->readonly = 0;
484         imap_free_msgids();
485         cprintf("%s OK CLOSE completed\r\n", parms[0]);
486 }
487
488
489
490
491 /*
492  * Used by LIST and LSUB to show the floors in the listing
493  */
494 void imap_list_floors(char *cmd, char *pattern) {
495         int i;
496         struct floor *fl;
497
498         for (i=0; i<MAXFLOORS; ++i) {
499                 fl = cgetfloor(i);
500                 if (fl->f_flags & F_INUSE) {
501                         if (imap_mailbox_matches_pattern(pattern, fl->f_name)) {
502                                 cprintf("* %s (\\NoSelect) \"|\" ", cmd);
503                                 imap_strout(fl->f_name);
504                                 cprintf("\r\n");
505                         }
506                 }
507         }
508 }
509
510
511
512 /*
513  * Back end for imap_lsub()
514  *
515  * IMAP "subscribed folder" is equivocated to Citadel "known rooms."  This
516  * may or may not be the desired behavior in the future.
517  */
518 void imap_lsub_listroom(struct quickroom *qrbuf, void *data) {
519         char buf[SIZ];
520         int ra;
521         char *pattern;
522
523         pattern = (char *)data;
524
525         /* Only list rooms to which the user has access!! */
526         ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
527         if (ra & UA_KNOWN) {
528                 imap_mailboxname(buf, sizeof buf, qrbuf);
529                 if (imap_mailbox_matches_pattern(pattern, buf)) {
530                         cprintf("* LSUB (");
531                         if (!strcasecmp(buf, "INBOX")) {
532                                 cprintf("\\NoInferiors");
533                         }
534                         cprintf(") \"|\" ");
535                         imap_strout(buf);
536                         cprintf("\r\n");
537                 }
538         }
539 }
540
541
542 /*
543  * Implements the LSUB command
544  */
545 void imap_lsub(int num_parms, char *parms[]) {
546         char pattern[SIZ];
547         if (num_parms < 4) {
548                 cprintf("%s BAD arguments invalid\r\n", parms[0]);
549                 return;
550         }
551         snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
552
553         if (strlen(parms[3])==0) {
554                 cprintf("* LIST (\\Noselect) \"|\" \"\"\r\n");
555         }
556
557         else {
558                 imap_list_floors("LSUB", pattern);
559                 ForEachRoom(imap_lsub_listroom, pattern);
560         }
561
562         cprintf("%s OK LSUB completed\r\n", parms[0]);
563 }
564
565
566
567 /*
568  * Back end for imap_list()
569  */
570 void imap_list_listroom(struct quickroom *qrbuf, void *data) {
571         char buf[SIZ];
572         int ra;
573         char *pattern;
574
575         pattern = (char *)data;
576
577         /* Only list rooms to which the user has access!! */
578         ra = CtdlRoomAccess(qrbuf, &CC->usersupp);
579         if ( (ra & UA_KNOWN) 
580           || ((ra & UA_GOTOALLOWED) && (ra & UA_ZAPPED))) {
581                 imap_mailboxname(buf, sizeof buf, qrbuf);
582                 if (imap_mailbox_matches_pattern(pattern, buf)) {
583                         cprintf("* LIST (");
584                         if (!strcasecmp(buf, "INBOX")) {
585                                 cprintf("\\NoInferiors");
586                         }
587                         cprintf(") \"|\" ");
588                         imap_strout(buf);
589                         cprintf("\r\n");
590                 }
591         }
592 }
593
594
595 /*
596  * Implements the LIST command
597  */
598 void imap_list(int num_parms, char *parms[]) {
599         char pattern[SIZ];
600         if (num_parms < 4) {
601                 cprintf("%s BAD arguments invalid\r\n", parms[0]);
602                 return;
603         }
604         snprintf(pattern, sizeof pattern, "%s%s", parms[2], parms[3]);
605
606         if (strlen(parms[3])==0) {
607                 cprintf("* LIST (\\Noselect) \"|\" \"\"\r\n");
608         }
609
610         else {
611                 imap_list_floors("LIST", pattern);
612                 ForEachRoom(imap_list_listroom, pattern);
613         }
614
615         cprintf("%s OK LIST completed\r\n", parms[0]);
616 }
617
618
619
620 /*
621  * Implements the CREATE command
622  *
623  */
624 void imap_create(int num_parms, char *parms[]) {
625         int ret;
626         char roomname[ROOMNAMELEN];
627         int floornum;
628         int flags;
629         int newroomtype;
630
631         ret = imap_roomname(roomname, sizeof roomname, parms[2]);
632         if (ret < 0) {
633                 cprintf("%s NO Invalid mailbox name or location\r\n",
634                         parms[0]);
635                 return;
636         }
637         floornum = ( ret & 0x00ff );    /* lower 8 bits = floor number */
638         flags =    ( ret & 0xff00 );    /* upper 8 bits = flags        */
639
640         if (flags & IR_MAILBOX) {
641                 newroomtype = 4;        /* private mailbox */
642         }
643         else {
644                 newroomtype = 0;        /* public folder */
645         }
646
647         lprintf(7, "Create new room <%s> on floor <%d> with type <%d>\n",
648                 roomname, floornum, newroomtype);
649
650         ret = create_room(roomname, newroomtype, "", floornum, 1);
651         if (ret == 0) {
652                 cprintf("%s NO Mailbox already exists, or create failed\r\n",
653                         parms[0]);
654         }
655         else {
656                 cprintf("%s OK CREATE completed\r\n", parms[0]);
657         }
658 }
659
660
661 /*
662  * Locate a room by its IMAP folder name, and check access to it
663  */
664 int imap_grabroom(char *returned_roomname, char *foldername) {
665         int ret;
666         char augmented_roomname[ROOMNAMELEN];
667         char roomname[ROOMNAMELEN];
668         int c;
669         struct quickroom QRscratch;
670         int ra;
671         int ok = 0;
672
673         ret = imap_roomname(roomname, sizeof roomname, foldername);
674         if (ret < 0) {
675                 return(1);
676         }
677
678         /* First try a regular match */
679         c = getroom(&QRscratch, roomname);
680
681         /* Then try a mailbox name match */
682         if (c != 0) {
683                 MailboxName(augmented_roomname, sizeof augmented_roomname,
684                             &CC->usersupp, roomname);
685                 c = getroom(&QRscratch, augmented_roomname);
686                 if (c == 0)
687                         strcpy(roomname, augmented_roomname);
688         }
689
690         /* If the room exists, check security/access */
691         if (c == 0) {
692                 /* See if there is an existing user/room relationship */
693                 ra = CtdlRoomAccess(&QRscratch, &CC->usersupp);
694
695                 /* normal clients have to pass through security */
696                 if (ra & UA_KNOWN) {
697                         ok = 1;
698                 }
699         }
700
701         /* Fail here if no such room */
702         if (!ok) {
703                 strcpy(returned_roomname, "");
704                 return(2);
705         }
706         else {
707                 strcpy(returned_roomname, QRscratch.QRname);
708                 return(0);
709         }
710 }
711
712
713 /*
714  * Implements the STATUS command (sort of)
715  *
716  */
717 void imap_status(int num_parms, char *parms[]) {
718         int ret;
719         char roomname[ROOMNAMELEN];
720         char buf[SIZ];
721         char savedroom[ROOMNAMELEN];
722         int msgs, new;
723
724         ret = imap_grabroom(roomname, parms[2]);
725         if (ret != 0) {
726                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
727                         parms[0]);
728                 return;
729         }
730
731         /*
732          * usergoto() formally takes us to the desired room, happily returning
733          * the number of messages and number of new messages.  (If another
734          * folder is selected, save its name so we can return there!!!!!)
735          */
736         if (IMAP->selected) {
737                 strcpy(savedroom, CC->quickroom.QRname);
738         }
739         usergoto(roomname, 0, &msgs, &new);
740
741         /*
742          * Tell the client what it wants to know.  In fact, tell it *more* than
743          * it wants to know.  We happily IGnore the supplied status data item
744          * names and simply spew all possible data items.  It's far easier to
745          * code and probably saves us some processing time too.
746          */
747         imap_mailboxname(buf, sizeof buf, &CC->quickroom);
748         cprintf("* STATUS ");
749         imap_strout(buf);
750         cprintf(" (MESSAGES %d ", msgs);
751         cprintf("RECENT 0 ");   /* FIXME we need to implement this */
752         cprintf("UIDNEXT %ld ", CitControl.MMhighest + 1);
753         cprintf("UNSEEN %d)\r\n", new);
754
755         /*
756          * If another folder is selected, go back to that room so we can resume
757          * our happy day without violent explosions.
758          */
759         if (IMAP->selected) {
760                 usergoto(savedroom, 0, &msgs, &new);
761         }
762
763         /*
764          * Oooh, look, we're done!
765          */
766         cprintf("%s OK STATUS completed\r\n", parms[0]);
767 }
768
769
770
771 /*
772  * Implements the SUBSCRIBE command
773  *
774  */
775 void imap_subscribe(int num_parms, char *parms[]) {
776         int ret;
777         char roomname[ROOMNAMELEN];
778         char savedroom[ROOMNAMELEN];
779         int msgs, new;
780
781         ret = imap_grabroom(roomname, parms[2]);
782         if (ret != 0) {
783                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
784                         parms[0]);
785                 return;
786         }
787
788         /*
789          * usergoto() formally takes us to the desired room, which has the side
790          * effect of marking the room as not-zapped ... exactly the effect
791          * we're looking for.
792          */
793         if (IMAP->selected) {
794                 strcpy(savedroom, CC->quickroom.QRname);
795         }
796         usergoto(roomname, 0, &msgs, &new);
797
798         /*
799          * If another folder is selected, go back to that room so we can resume
800          * our happy day without violent explosions.
801          */
802         if (IMAP->selected) {
803                 usergoto(savedroom, 0, &msgs, &new);
804         }
805
806         cprintf("%s OK SUBSCRIBE completed\r\n", parms[0]);
807 }
808
809
810 /*
811  * Implements the UNSUBSCRIBE command
812  *
813  */
814 void imap_unsubscribe(int num_parms, char *parms[]) {
815         int ret;
816         char roomname[ROOMNAMELEN];
817         char savedroom[ROOMNAMELEN];
818         int msgs, new;
819
820         ret = imap_grabroom(roomname, parms[2]);
821         if (ret != 0) {
822                 cprintf("%s NO Invalid mailbox name or location, or access denied\r\n",
823                         parms[0]);
824                 return;
825         }
826
827         /*
828          * usergoto() formally takes us to the desired room.
829          */
830         if (IMAP->selected) {
831                 strcpy(savedroom, CC->quickroom.QRname);
832         }
833         usergoto(roomname, 0, &msgs, &new);
834
835         /* 
836          * Now make the API call to zap the room
837          */
838         if (CtdlForgetThisRoom() == 0) {
839                 cprintf("%s OK UNSUBSCRIBE completed\r\n", parms[0]);
840         }
841         else {
842                 cprintf("%s NO You may not unsubscribe from this folder.\r\n",
843                         parms[0]);
844         }
845
846         /*
847          * If another folder is selected, go back to that room so we can resume
848          * our happy day without violent explosions.
849          */
850         if (IMAP->selected) {
851                 usergoto(savedroom, 0, &msgs, &new);
852         }
853 }
854
855
856
857 /*
858  * Implements the DELETE command
859  *
860  */
861 void imap_delete(int num_parms, char *parms[]) {
862         int ret;
863         char roomname[ROOMNAMELEN];
864         char savedroom[ROOMNAMELEN];
865         int msgs, new;
866
867         ret = imap_grabroom(roomname, parms[2]);
868         if (ret != 0) {
869                 cprintf("%s NO Invalid mailbox name, or access denied\r\n",
870                         parms[0]);
871                 return;
872         }
873
874         /*
875          * usergoto() formally takes us to the desired room, happily returning
876          * the number of messages and number of new messages.  (If another
877          * folder is selected, save its name so we can return there!!!!!)
878          */
879         if (IMAP->selected) {
880                 strcpy(savedroom, CC->quickroom.QRname);
881         }
882         usergoto(roomname, 0, &msgs, &new);
883
884         /*
885          * Now delete the room.
886          */
887         if (CtdlDoIHavePermissionToDeleteThisRoom(&CC->quickroom)) {
888                 cprintf("%s OK DELETE completed\r\n", parms[0]);
889                 delete_room(&CC->quickroom);
890         }
891         else {
892                 cprintf("%s NO Can't delete this folder.\r\n", parms[0]);
893         }
894
895         /*
896          * If another folder is selected, go back to that room so we can resume
897          * our happy day without violent explosions.
898          */
899         if (IMAP->selected) {
900                 usergoto(savedroom, 0, &msgs, &new);
901         }
902 }
903
904
905
906 /*
907  * Implements the RENAME command
908  *
909  */
910 void imap_rename(int num_parms, char *parms[]) {
911         cprintf("%s NO The RENAME command is not yet implemented (FIXME)\r\n",
912                 parms[0]);
913 }
914
915
916
917 /* 
918  * Main command loop for IMAP sessions.
919  */
920 void imap_command_loop(void) {
921         char cmdbuf[SIZ];
922         char *parms[SIZ];
923         int num_parms;
924
925         time(&CC->lastcmd);
926         memset(cmdbuf, 0, sizeof cmdbuf); /* Clear it, just in case */
927         if (client_gets(cmdbuf) < 1) {
928                 lprintf(3, "IMAP socket is broken.  Ending session.\r\n");
929                 CC->kill_me = 1;
930                 return;
931         }
932
933         lprintf(5, "IMAP: %s\r\n", cmdbuf);
934         while (strlen(cmdbuf) < 5) strcat(cmdbuf, " ");
935
936
937         /* strip off l/t whitespace and CRLF */
938         if (cmdbuf[strlen(cmdbuf)-1]=='\n') cmdbuf[strlen(cmdbuf)-1]=0;
939         if (cmdbuf[strlen(cmdbuf)-1]=='\r') cmdbuf[strlen(cmdbuf)-1]=0;
940         striplt(cmdbuf);
941
942         /* If we're in the middle of a multi-line command, handle that */
943         if (IMAP->authstate == imap_as_expecting_username) {
944                 imap_auth_login_user(cmdbuf);
945                 return;
946         }
947         if (IMAP->authstate == imap_as_expecting_password) {
948                 imap_auth_login_pass(cmdbuf);
949                 return;
950         }
951
952
953         /* Ok, at this point we're in normal command mode.  The first thing
954          * we do is print any incoming pages (yeah! we really do!)
955          */
956         imap_print_express_messages();
957
958         /*
959          * Before processing the command that was just entered... if we happen
960          * to have a folder selected, we'd like to rescan that folder for new
961          * messages, and for deletions/changes of existing messages.  This
962          * could probably be optimized somehow, but IMAP sucks...
963          */
964         if (IMAP->selected) {
965                 imap_rescan_msgids();
966         }
967
968         /* Now for the command set. */
969
970         /* Grab the tag, command, and parameters.  Check syntax. */
971         num_parms = imap_parameterize(parms, cmdbuf);
972         if (num_parms < 2) {
973                 cprintf("BAD syntax error\r\n");
974         }
975
976         /* The commands below may be executed in any state */
977
978         else if ( (!strcasecmp(parms[1], "NOOP"))
979            || (!strcasecmp(parms[1], "CHECK")) ) {
980                 cprintf("%s OK This command successfully did nothing.\r\n",
981                         parms[0]);
982         }
983
984         else if (!strcasecmp(parms[1], "LOGOUT")) {
985                 cprintf("* BYE %s logging out\r\n", config.c_fqdn);
986                 cprintf("%s OK thank you for using Citadel IMAP\r\n", parms[0]);
987                 CC->kill_me = 1;
988                 return;
989         }
990
991         else if (!strcasecmp(parms[1], "LOGIN")) {
992                 imap_login(num_parms, parms);
993         }
994
995         else if (!strcasecmp(parms[1], "AUTHENTICATE")) {
996                 imap_authenticate(num_parms, parms);
997         }
998
999         else if (!strcasecmp(parms[1], "CAPABILITY")) {
1000                 imap_capability(num_parms, parms);
1001         }
1002
1003         else if (!CC->logged_in) {
1004                 cprintf("%s BAD Not logged in.\r\n", parms[0]);
1005         }
1006
1007         /* The commans below require a logged-in state */
1008
1009         else if (!strcasecmp(parms[1], "SELECT")) {
1010                 imap_select(num_parms, parms);
1011         }
1012
1013         else if (!strcasecmp(parms[1], "EXAMINE")) {
1014                 imap_select(num_parms, parms);
1015         }
1016
1017         else if (!strcasecmp(parms[1], "LSUB")) {
1018                 imap_lsub(num_parms, parms);
1019         }
1020
1021         else if (!strcasecmp(parms[1], "LIST")) {
1022                 imap_list(num_parms, parms);
1023         }
1024
1025         else if (!strcasecmp(parms[1], "CREATE")) {
1026                 imap_create(num_parms, parms);
1027         }
1028
1029         else if (!strcasecmp(parms[1], "DELETE")) {
1030                 imap_delete(num_parms, parms);
1031         }
1032
1033         else if (!strcasecmp(parms[1], "RENAME")) {
1034                 imap_rename(num_parms, parms);
1035         }
1036
1037         else if (!strcasecmp(parms[1], "STATUS")) {
1038                 imap_status(num_parms, parms);
1039         }
1040
1041         else if (!strcasecmp(parms[1], "SUBSCRIBE")) {
1042                 imap_subscribe(num_parms, parms);
1043         }
1044
1045         else if (!strcasecmp(parms[1], "UNSUBSCRIBE")) {
1046                 imap_unsubscribe(num_parms, parms);
1047         }
1048
1049         else if (!strcasecmp(parms[1], "APPEND")) {
1050                 imap_append(num_parms, parms);
1051         }
1052
1053         else if (IMAP->selected == 0) {
1054                 cprintf("%s BAD no folder selected\r\n", parms[0]);
1055         }
1056
1057         /* The commands below require the SELECT state on a mailbox */
1058
1059         else if (!strcasecmp(parms[1], "FETCH")) {
1060                 imap_fetch(num_parms, parms);
1061         }
1062
1063         else if ( (!strcasecmp(parms[1], "UID"))
1064                 && (!strcasecmp(parms[2], "FETCH")) ) {
1065                 imap_uidfetch(num_parms, parms);
1066         }
1067
1068         else if (!strcasecmp(parms[1], "SEARCH")) {
1069                 imap_search(num_parms, parms);
1070         }
1071
1072         else if ( (!strcasecmp(parms[1], "UID"))
1073                 && (!strcasecmp(parms[2], "SEARCH")) ) {
1074                 imap_uidsearch(num_parms, parms);
1075         }
1076
1077         else if (!strcasecmp(parms[1], "STORE")) {
1078                 imap_store(num_parms, parms);
1079         }
1080
1081         else if ( (!strcasecmp(parms[1], "UID"))
1082                 && (!strcasecmp(parms[2], "STORE")) ) {
1083                 imap_uidstore(num_parms, parms);
1084         }
1085
1086         else if (!strcasecmp(parms[1], "COPY")) {
1087                 imap_copy(num_parms, parms);
1088         }
1089
1090         else if ( (!strcasecmp(parms[1], "UID"))
1091                 && (!strcasecmp(parms[2], "COPY")) ) {
1092                 imap_uidcopy(num_parms, parms);
1093         }
1094
1095         else if (!strcasecmp(parms[1], "EXPUNGE")) {
1096                 imap_expunge(num_parms, parms);
1097         }
1098
1099         else if (!strcasecmp(parms[1], "CLOSE")) {
1100                 imap_close(num_parms, parms);
1101         }
1102
1103         /* End of commands.  If we get here, the command is either invalid
1104          * or unimplemented.
1105          */
1106
1107         else {
1108                 cprintf("%s BAD command unrecognized\r\n", parms[0]);
1109         }
1110
1111         /* If the client transmitted a message we can free it now */
1112         imap_free_transmitted_message();
1113 }
1114
1115
1116
1117 /*
1118  * This function is called by dynloader.c to register the IMAP module
1119  * with the Citadel server.
1120  */
1121 char *Dynamic_Module_Init(void)
1122 {
1123         SYM_IMAP = CtdlGetDynamicSymbol();
1124         CtdlRegisterServiceHook(config.c_imap_port,
1125                                 NULL,
1126                                 imap_greeting,
1127                                 imap_command_loop);
1128         CtdlRegisterSessionHook(imap_cleanup_function, EVT_STOP);
1129         return "$Id$";
1130 }