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