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